Improve LLM context with full timestamped channel history
Send last ~8 messages from all users (not just others) as a multi-line chat log with relative timestamps so the LLM can better understand conversation flow and escalation patterns. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -657,23 +657,54 @@ class SentimentCog(commands.Cog):
|
||||
ch_id = message.channel.id
|
||||
if ch_id not in self._channel_history:
|
||||
max_ctx = self.bot.config.get("sentiment", {}).get(
|
||||
"context_messages", 3
|
||||
"context_messages", 8
|
||||
)
|
||||
self._channel_history[ch_id] = deque(maxlen=max_ctx + 1)
|
||||
self._channel_history[ch_id] = deque(maxlen=max_ctx)
|
||||
self._channel_history[ch_id].append(
|
||||
(message.author.display_name, message.content)
|
||||
(message.author.display_name, message.content, datetime.now(timezone.utc))
|
||||
)
|
||||
|
||||
def _get_context(self, message: discord.Message) -> str:
|
||||
"""Build a timestamped chat log from recent channel messages.
|
||||
|
||||
Excludes messages currently buffered for this user+channel
|
||||
(those appear in the TARGET MESSAGE section instead).
|
||||
"""
|
||||
ch_id = message.channel.id
|
||||
history = self._channel_history.get(ch_id, deque())
|
||||
# Exclude the current message (last item)
|
||||
context_entries = list(history)[:-1] if len(history) > 1 else []
|
||||
if not context_entries:
|
||||
if not history:
|
||||
return "(no prior context)"
|
||||
return " | ".join(
|
||||
f"{name}: {content}" for name, content in context_entries
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Collect IDs of messages in the current debounce batch so we can skip them
|
||||
batch_key = (ch_id, message.author.id)
|
||||
batch_msgs = self._message_buffer.get(batch_key, [])
|
||||
# Build a set of (author, content) from the batch for fast lookup
|
||||
batch_set = {(m.author.display_name, m.content) for m in batch_msgs}
|
||||
|
||||
lines = []
|
||||
for name, content, ts in history:
|
||||
if (name, content) in batch_set:
|
||||
continue
|
||||
delta = now - ts
|
||||
rel = self._format_relative_time(delta)
|
||||
lines.append(f"[{rel}] {name}: {content}")
|
||||
|
||||
if not lines:
|
||||
return "(no prior context)"
|
||||
return "\n".join(lines)
|
||||
|
||||
@staticmethod
|
||||
def _format_relative_time(delta: timedelta) -> str:
|
||||
total_seconds = int(delta.total_seconds())
|
||||
if total_seconds < 60:
|
||||
return f"~{total_seconds}s ago"
|
||||
minutes = total_seconds // 60
|
||||
if minutes < 60:
|
||||
return f"~{minutes}m ago"
|
||||
hours = minutes // 60
|
||||
return f"~{hours}h ago"
|
||||
|
||||
async def _log_analysis(
|
||||
self, message: discord.Message, score: float, drama_score: float,
|
||||
|
||||
Reference in New Issue
Block a user