Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,8 @@ while tool_calls and rounds < profile.max_rounds:
### Trajectory Replay (`CONVERSATIONS_TRAJECTORY_*`)
Each turn captures the **exact rendered user message** plus the serialized internal loop (assistant tool calls, tool results, final answer). On follow-ups, the most recent `CONVERSATIONS_TRAJECTORY_TURNS` turns are replayed **verbatim** — the model literally sees its own prior tool calls and their results instead of a distilled Q/A pair. Older turns (and turns captured before this feature, or whose trajectory was dropped as invalid/oversized) fall back to the compact attributed rendering.

Everyone in a conversation is the `user` role, so when the speaker changes from one turn to the next the `[Por …]` tag says so (`outra pessoa — antes falava Ana (@ana)`). The mark is written when the turn is captured, so verbatim replay keeps it without re-rendering; compact turns get the same mark.

Replay windows advance in `CONVERSATIONS_TRAJECTORY_STEP`-turn steps (hysteresis), so the replayed prefix only changes at deliberate collapse boundaries — not sliding every turn — which is what keeps the provider prefix cache effective. Explicit `cache_control` breakpoints mark the system prompt and the last replayed history message for Anthropic/Gemini via OpenRouter; OpenAI-compatible endpoints ignore them and cache automatically. Captured trajectories are sanitized on persist (no `reasoning`/thinking payloads, tool-call/result pairing enforced).

### Rate Limiting
Expand All @@ -373,7 +375,7 @@ Conversations (`/chat`, `/ask`, mentions, replies, name calls, monitors) use the
### Context Injection
Every AI call receives a `<contexto>` block with user (display name, account age, join date, roles), guild (name, member count, channels, roles), channel, and temporal (BRT + UTC) context, plus a `<canal>` block with the channel's `instructions` setting when it has one.

When `CHANNEL_CONTEXT_MESSAGES` > 0 (default `30`), every conversational turn also receives a `<mensagens_recentes_do_canal>` block — the latest N channel messages in chronological order, trimmed from the oldest side to `CHANNEL_CONTEXT_MAX_CHARS` (in a fast chat ten messages is a minute of talk, and what "esse sinal" points at can be further back), same format as the `get_channel_history` tool. Image attachments in that context are persisted and sent as vision parts, up to the four-image per-message budget (current-message images take priority, then the newest channel images); filenames remain visible in the text context. Only images posted within `CHANNEL_CONTEXT_IMAGE_MAX_AGE_MINUTES` (default `60`) are sent, and `CHANNEL_CONTEXT_IMAGES_ENABLED=false` turns channel images off entirely (use it with text-only `CHAT_MODEL`s). Attachments are downloaded once and reused by attachment id. Stickers (`[figurinha:Nome]`) and GIF/image link embeds (Tenor, Giphy, direct image links; `[gif: …]`) count as images too; animated GIFs and stickers are sent as one numbered sheet of four evenly spaced frames, and Tenor/Giphy links use a small animated rendition with the still preview as fallback. Lottie stickers are shown by name only. Custom emojis appear as `:nome:` in the text, and each message's custom emojis are drawn on one labelled sheet that only uses image slots left over after real media. The same media from the triggering message (and the message it replies to) is sent as the user's own images. Reactions are listed on each line before `msg_id` as `[reações: 👍 3 (Ana, Bruno +1)]`, with up to `REACTION_USERS_LIMIT` reactor names per reaction. The triggering message is excluded; set `0` to disable. Reply follow-ups use the captured gap block (`prior_context`, see `CONVERSATIONS_GAP_MESSAGES`) instead of this recent-channel window whenever a gap was captured, including images from those gap messages.
When `CHANNEL_CONTEXT_MESSAGES` > 0 (default `30`), every conversational turn also receives a `<mensagens_recentes_do_canal>` block — the latest N channel messages in chronological order, trimmed from the oldest side to `CHANNEL_CONTEXT_MAX_CHARS` (in a fast chat ten messages is a minute of talk, and what "esse sinal" points at can be further back), same format as the `get_channel_history` tool. Image attachments in that context are persisted and sent as vision parts, up to the four-image per-message budget (current-message images take priority, then the newest channel images); filenames remain visible in the text context. Only images posted within `CHANNEL_CONTEXT_IMAGE_MAX_AGE_MINUTES` (default `60`) are sent, and `CHANNEL_CONTEXT_IMAGES_ENABLED=false` turns channel images off entirely (use it with text-only `CHAT_MODEL`s). Attachments are downloaded once and reused by attachment id. Stickers (`[figurinha:Nome]`) and GIF/image link embeds (Tenor, Giphy, direct image links; `[gif: …]`) count as images too; animated GIFs and stickers are sent as one numbered sheet of four evenly spaced frames, and Tenor/Giphy links use a small animated rendition with the still preview as fallback. Lottie stickers are shown by name only. Custom emojis appear as `:nome:` in the text, and each message's custom emojis are drawn on one labelled sheet that only uses image slots left over after real media. The same media from the triggering message (and the message it replies to) is sent as the user's own images. Reactions are listed on each line before `msg_id` as `[reações: 👍 3 (Ana, Bruno +1)]`, with up to `REACTION_USERS_LIMIT` reactor names per reaction. The triggering message is excluded; set `0` to disable. The block opens with a note that it is only context, and the system prompt tells the model that everything above the question's `[Por …]` tag is background: it answers only what that person wrote, and uses the channel's other messages to understand it, not to answer them. Reply follow-ups use the captured gap block (`prior_context`, see `CONVERSATIONS_GAP_MESSAGES`) instead of this recent-channel window whenever a gap was captured, including images from those gap messages.

### Prefix-Cache-Friendly Message Layout
The LLM message list is ordered so conversation follow-ups reuse a cached prefix: `[system (persona + static conversation summary)] → [replayed history turns] → [current message]`. All per-request blocks — `<contexto>` (clock), the semantically-selected memory block, and the recent channel window — ride on the **final user message** instead of the system prompt, so the system prompt + history stay byte-identical across turns and providers can prefix-cache them (typically 80–95% input-token savings on cached prefixes).
Expand Down Expand Up @@ -751,10 +753,11 @@ ruff check . # lint (rules configured in pyproject.toml)
| File | Covers |
|---|---|
| `test_api_logger.py` | Request logging for aiohttp/httpx/httpx2, redaction, body capture, inbound interactions (runs in its own process) |
| `test_attribution.py` | Author tags on every question, byte-identical replay of per-turn blocks, memory block labels and person-memory rules |
| `test_attribution.py` | Author tags on every question, speaker changes marked in the tag (verbatim and compact replay), the conversation block naming who speaks now, byte-identical replay of per-turn blocks, memory block labels and person-memory rules |
| `test_channel_context_images.py` | Images from automatically fetched channel context |
| `test_chat_threads.py` | When conversations move into threads (incl. the `threads` setting; one person's back-and-forth, not name calls or a group), delivery and pings, reusing a moved conversation's thread, mentions and name calls in the channel not following it there, un-mentioned messages and silence in bot threads, the `open_thread` tool (only for long or off-topic subjects), the model naming threads it opens on its own (falling back to the first question) |
| `test_context_and_requests.py` | The wider channel window and its budget, waiting for the image after "ai oh @bot", sharper shown images labelled apart from channel images, the search hint |
| `test_context_framing.py` | Channel chatter labelled as context (recent window and gap block), the prompt saying to answer only the tagged message, the new speaker marked in the real request |
| `test_conversation_flow.py` | Bursts (follow-ups while answering only after a mention or reply), budget, name calls, aliases and `respond` settings, channel instructions, reply style, staying quiet, edits and deletes, `/chat` and `/ask` |
| `test_delivery.py` | Plain vs embed, splitting long answers (code blocks stay valid), real pings for humans only, sources line, threads |
| `test_conversation_participants.py` | Participant scope for shared conversations and memory writes |
Expand Down
10 changes: 9 additions & 1 deletion core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
CONVERSATIONS_GAP_MESSAGES,
)
from core import image_store, message_media
from core.conversations import CONTEXT_ONLY_NOTE
from core.discord_text import _fmt_dt, format_message_lines

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -276,6 +277,9 @@ async def fetch_recent_channel_context(
when disabled or without a readable channel. Image attachments are
persisted and returned separately from the formatted text. ``before``
excludes the triggering message from the window (mention/follow-up flows).
The block opens with a note that it is background: the window rides in
the same user message as the question, and without it the model answers
the channel's other topics too.
"""
n = CHANNEL_CONTEXT_MESSAGES if limit is None else limit
if n <= 0 or channel is None:
Expand All @@ -291,7 +295,11 @@ async def fetch_recent_channel_context(
getattr(channel, 'id', None), len(context.lines), len(context.images),
)
return ChannelContext(
text=f"<mensagens_recentes_do_canal>\n{context.text}\n</mensagens_recentes_do_canal>",
text=(
"<mensagens_recentes_do_canal>\n"
f"(O que o canal falava antes da mensagem que você vai responder — {CONTEXT_ONLY_NOTE}.)\n"
f"{context.text}\n</mensagens_recentes_do_canal>"
),
lines=context.lines,
images=context.images,
)
Expand Down
63 changes: 47 additions & 16 deletions core/conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@
logger = logging.getLogger(__name__)

PRIOR_CONTEXT_HEADER = 'Mensagens no canal antes desta pergunta'
# Labels the channel messages a turn carries as background: they were written
# for the channel, not to the bot, and are only there to understand the question.
CONTEXT_ONLY_NOTE = 'só contexto: não são pedidos para você'
# Expired conversations waiting for their episode summary are dropped after this.
EPISODE_GRACE_SECONDS = 24 * 3600

Expand Down Expand Up @@ -429,13 +432,30 @@ def _author_label(author: dict | None) -> str:
return f'{display} (@{name})' if name else display


def speaker_change(previous: dict | None, author: dict | None) -> str:
"""``outra pessoa — antes falava …`` when *author* is not who spoke in the previous turn, else ``''``.

In a shared conversation every person is the ``user`` role, so without
this the only sign that someone else took over is the name in the tag,
which models easily read past.
"""
prev_id = str((previous or {}).get('id') or '')
author_id = str((author or {}).get('id') or '')
if not prev_id or not author_id or prev_id == author_id:
return ''
return f'outra pessoa — antes falava {_author_label(previous)}'


def author_tag(
author: dict | None, ts: float | None, *, reply_to: str | int | None = None,
previous: dict | None = None,
) -> str:
"""``[Por Autor (@handle) • author_id=… • data hora]`` or ``''`` without an author.

Used on every user message sent to the LLM. It never says "now", so the
stored copy stays accurate when replayed byte-identically in later turns.
*previous* is the author of the conversation's previous turn: when it is
someone else, the tag says so (:func:`speaker_change`).
"""
a = author or {}
if not (a.get('id') or a.get('name') or a.get('display')):
Expand All @@ -444,6 +464,9 @@ def author_tag(
if a.get('id'):
meta.append(f"author_id={a['id']}")
meta.append(_fmt_ts(ts))
change = speaker_change(previous, a)
if change:
meta.append(change)
if reply_to:
meta.append(f'↩ reply_to={reply_to}')
return f"[{' • '.join(meta)}]"
Expand All @@ -462,9 +485,8 @@ def _prior_context_head(lines: list[str], channel_id: str | int | None) -> str:
"""Render the prior-context header (with channel when known) and its lines."""
if not lines:
return ''
header = f'[{PRIOR_CONTEXT_HEADER}]'
if channel_id:
header = f'[{PRIOR_CONTEXT_HEADER} (channel_id={channel_id})]'
where = f' (channel_id={channel_id})' if channel_id else ''
header = f'[{PRIOR_CONTEXT_HEADER}{where} — {CONTEXT_ONLY_NOTE}]'
return header + '\n' + '\n'.join(lines) + '\n\n'


Expand Down Expand Up @@ -578,7 +600,8 @@ def build_history_messages(
``↩ reply_to=``, ``msg_id=``), channel chatter captured between turns
(``prior_context``) is injected above the question, and sources used in a
turn are appended to its assistant message. Verbatim turns rely on the
attribution baked into their captured text instead of these prefixes.
attribution baked into their captured text instead of these prefixes
(:func:`build_current_message` writes the same speaker change there).

Both windows advance in ``trajectory_step`` increments (see
:func:`stepped_floor`) so the rendered history only changes at deliberate
Expand Down Expand Up @@ -608,26 +631,26 @@ def build_history_messages(
verbatim_from = min(len(turns), verbatim_from + step)

messages: list[dict] = []
prev_author_id: str | None = None
prev_author: dict | None = None
image_budget = max_images
inline_from = max(0, len(turns) - image_turns)
for idx, turn in enumerate(turns):
author = turn.get('author') or {}
previous, prev_author = prev_author, author
if idx >= verbatim_from:
replayed = _replay_verbatim_turn(turn, image_budget)
if replayed is not None:
replayed_messages, images_used = replayed
image_budget -= images_used
messages.extend(replayed_messages)
continue
author = turn.get('author') or {}
meta = [f"Por {_author_label(author)}"]
if author.get('id'):
meta.append(f"author_id={author['id']}")
meta.append(_fmt_ts(turn.get('ts')))
author_id = author.get('id')
if prev_author_id is not None and author_id and author_id != prev_author_id:
meta.append('nova pessoa na conversa')
prev_author_id = author_id
change = speaker_change(previous, author)
if change:
meta.append(change)
if turn.get('reply_to'):
meta.append(f"↩ reply_to={turn['reply_to']}")
if turn.get('message_id'):
Expand Down Expand Up @@ -673,6 +696,7 @@ def build_current_message(
channel_id: str | int | None = None,
context_blocks: str | None = None,
context_image_urls: list[str] | None = None,
previous_author: dict | None = None,
) -> dict:
"""Build the current user message, attributed to its author (:func:`author_tag`).

Expand All @@ -681,6 +705,9 @@ def build_current_message(
persisted images from that context. Keeping both in the *tail* message —
instead of the system prompt — leaves the history prefix byte-identical
across follow-ups, which makes provider prefix caching effective.
``previous_author`` (who spoke in the conversation's previous turn) marks
a change of speaker in the tag; it is stored with the turn, so verbatim
replay keeps it without re-rendering.
"""
current_images, context_images, dropped = select_image_refs(image_urls, context_image_urls)
inline: list[dict] = []
Expand All @@ -689,7 +716,7 @@ def build_current_message(
[line for line in (prior_context or []) if line], channel_id
)
text = question
tag = author_tag(author, ts, reply_to=reply_to)
tag = author_tag(author, ts, reply_to=reply_to, previous=previous_author)
if tag:
# The tag sits right above the question — also on the first turn — so
# the asker is never inferred from the last channel line above it. It
Expand Down Expand Up @@ -729,7 +756,8 @@ def build_conversation_block(history: list[dict]) -> str:
never on the current request's clock or current sender. This lets the
rendered history that follows it stay byte-identical across follow-ups so
providers can prefix-cache it. The current sender is instead signalled by
the ``[Agora — …]`` prefix of the current message.
the ``[Por …]`` tag of the current message — which is why the participant
list says "até agora": whoever speaks now may not be in it yet.
"""
participants: list[dict] = []
for turn in history:
Expand All @@ -739,21 +767,24 @@ def build_conversation_block(history: list[dict]) -> str:
lines = [
'<conversa_em_andamento>',
f'Conversa iniciada em {_fmt_ts(start_ts)}.',
f'Participantes: {", ".join(_author_label(p) for p in participants)}.',
f'Participantes até agora: {", ".join(_author_label(p) for p in participants)}.',
]
if last_channel_id:
lines.append(f'Canal atual da conversa: channel_id={last_channel_id} (use com get_message_context).')
lines.extend([
'Cada mensagem de usuário traz, logo acima do texto, a marca [Por Autor (@usuário) • author_id=… • data hora] —',
'use essas marcas para saber quem perguntou o quê, e a qual resposta SUA (do bot) se referem.',
'A mensagem a que você deve responder agora é sempre a ÚLTIMA mensagem de usuário; as anteriores são histórico.',
'Mais de uma pessoa pode falar com você na mesma conversa: quando quem fala muda de uma mensagem para a',
'outra, a marca traz "outra pessoa — antes falava …".',
'Quem fala com você agora é o autor da marca [Por …] da ÚLTIMA mensagem de usuário — pode ser alguém que',
'ainda não participou. Responda a essa pessoa e ao que ela escreveu; as mensagens anteriores são histórico.',
'Cada mensagem pode trazer seus próprios blocos <contexto> e <memory>: eles descrevem o momento em que AQUELA',
'mensagem foi enviada (autor, horário, memórias da época). Se blocos de mensagens diferentes divergirem,',
'vale o da mensagem mais recente. Marcas antigas "[Agora — …]" também se referem ao momento da própria mensagem.',
'Mensagens do canal (ferramentas de histórico) usam o mesmo author_id/msg_id —',
'correlacione-as para saber quem disse o quê na conversa do canal.',
f'Blocos "[{PRIOR_CONTEXT_HEADER}]" trazem a conversa do canal',
'que aconteceu entre as perguntas direcionadas ao bot.',
f'Blocos "[{PRIOR_CONTEXT_HEADER} …]" trazem a conversa do canal',
'que aconteceu entre as perguntas direcionadas ao bot: só contexto, não pedidos para você.',
'Nos blocos de mensagens do canal, as suas respostas (do bot) e perguntas já registradas como '
'turnos são omitidas; use get_channel_history para vê-las.',
'</conversa_em_andamento>',
Expand Down
Loading
Loading