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
18 changes: 15 additions & 3 deletions astrbot/core/agent/context/round_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,25 @@ def split_into_rounds(
) -> list[list[RoundSegment]]:
"""Split a flat contexts list into logical rounds.
A round begins at a ``user`` segment and includes all subsequent
``assistant`` / ``tool`` segments until the next ``user`` segment.
A round begins at a user input and includes subsequent assistant, tool,
and generated user-role segments until the next user input. Generated
messages marked ``_turn_continuation`` do not start a new round.
Args:
contexts: Flat messages, optionally including a pre-user fragment.
Returns:
Logical rounds, with any pre-user fragment in a separate first group.
"""
rounds: list[list[RoundSegment]] = []
current: list[RoundSegment] = []
for seg in contexts:
if _segment_role(seg) == "user" and current:
starts_turn = _segment_role(seg) == "user" and not (
seg._turn_continuation
if isinstance(seg, Message)
else seg.get("_turn_continuation", False)
)
if starts_turn and current:
rounds.append(current)
current = []
current.append(seg)
Expand Down
81 changes: 41 additions & 40 deletions astrbot/core/agent/context/truncator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from typing import cast

from ..message import Message
from .round_utils import split_into_rounds


class ContextTruncator:
Expand All @@ -21,7 +24,7 @@ def _split_system_rest(
Returns:
tuple: (system_messages, non_system_messages)
"""
first_non_system = 0
first_non_system = len(messages)
for i, msg in enumerate(messages):
if msg.role != "system":
first_non_system = i
Expand Down Expand Up @@ -103,15 +106,21 @@ def truncate_by_turns(
keep_most_recent_turns: int,
drop_turns: int = 1,
) -> list[Message]:
"""
Turn-based truncation strategy, which drops the oldest turns while keeping the most recent N turns.
A turn consists of a user message and an assistant message.
This method ensures that the truncated context list conforms to OpenAI's context format.
"""Keep the most recent complete user turns when the limit is exceeded.
A turn starts at a user input and includes all subsequent assistant
messages, tool calls, tool results and generated user-role messages
until the next user input. A pre-user fragment does not count as a turn
and is discarded when truncation occurs.
The current, possibly unfinished turn counts towards the limit and is
always retained along with the leading system messages.
Args:
messages: The original list of messages in the context.
keep_most_recent_turns: The number of most recent turns to keep. If set to -1, it means keeping all turns (no truncation).
drop_turns: The number of turns to drop from the beginning.
drop_turns: Additional retention reduction on overflow. Retains
``keep_most_recent_turns - drop_turns + 1`` turns, with a minimum
of one so the current task is not discarded.
Returns:
The truncated list of messages.
Expand All @@ -120,56 +129,48 @@ def truncate_by_turns(
return messages

system_messages, non_system_messages = self._split_system_rest(messages)
rounds = cast(list[list[Message]], split_into_rounds(non_system_messages))
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
if rounds and (rounds[0][0].role != "user" or rounds[0][0]._turn_continuation):
rounds = rounds[1:]

if len(non_system_messages) // 2 <= keep_most_recent_turns:
if len(rounds) <= max(1, keep_most_recent_turns):
return messages

num_to_keep = keep_most_recent_turns - drop_turns + 1
if num_to_keep <= 0:
truncated_contexts = []
else:
truncated_contexts = non_system_messages[-num_to_keep * 2 :]

# Find the first user message
index = next(
(i for i, item in enumerate(truncated_contexts) if item.role == "user"),
None,
)
if index is not None and index > 0:
truncated_contexts = truncated_contexts[index:]

result = self._ensure_user_message(
system_messages, truncated_contexts, messages
)
num_to_keep = max(1, keep_most_recent_turns - drop_turns + 1)
result = system_messages + [msg for rnd in rounds[-num_to_keep:] for msg in rnd]
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
return self.fix_messages(result)

def truncate_by_dropping_oldest_turns(
self,
messages: list[Message],
drop_turns: int = 1,
) -> list[Message]:
"""Drop the oldest N turns, regardless of the number of turns to keep."""
"""Drop the oldest complete user turns while preserving the latest one.
A pre-user fragment is discarded along with the removed turns and
does not count towards the number of turns dropped.
Args:
messages: Context including any leading system messages.
drop_turns: Number of oldest turns to remove. Nonpositive values
disable truncation; at least the latest complete turn is kept.
Returns:
Context with leading system messages and the retained turns.
"""
if drop_turns <= 0:
return messages

system_messages, non_system_messages = self._split_system_rest(messages)
rounds = cast(list[list[Message]], split_into_rounds(non_system_messages))
if rounds and (rounds[0][0].role != "user" or rounds[0][0]._turn_continuation):
rounds = rounds[1:]

if len(non_system_messages) // 2 <= drop_turns:
truncated_non_system = []
else:
truncated_non_system = non_system_messages[drop_turns * 2 :]

# Find the first user message
index = next(
(i for i, item in enumerate(truncated_non_system) if item.role == "user"),
None,
)
if index is not None:
truncated_non_system = truncated_non_system[index:]
if len(rounds) <= 1:
return messages

result = self._ensure_user_message(
system_messages, truncated_non_system, messages
)
num_to_drop = min(drop_turns, len(rounds) - 1)
result = system_messages + [msg for rnd in rounds[num_to_drop:] for msg in rnd]
return self.fix_messages(result)

def truncate_by_halving(
Expand Down
14 changes: 10 additions & 4 deletions astrbot/core/agent/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ class Message(BaseModel):
"""The ID of the tool call."""

_no_save: bool = PrivateAttr(default=False)
_turn_continuation: bool = PrivateAttr(default=False)
"""Whether a generated user-role message continues the current user turn."""

@model_validator(mode="after")
def check_content_required(self):
Expand Down Expand Up @@ -255,13 +257,13 @@ class SystemMessageSegment(Message):


def load_messages(history: list[dict]) -> list[Message]:
"""Load working messages while restoring temporary-content markers.
"""Load working messages with temporary-content and turn-boundary markers.
Args:
history: Serialized conversation messages.
Returns:
Validated messages with their temporary-content markers restored.
Validated messages with their internal context markers restored.
Raises:
ValueError: A message has an invalid role or content.
Expand All @@ -271,6 +273,8 @@ def load_messages(history: list[dict]) -> list[Message]:
message = Message.model_validate(item)
if item.get("_no_save"):
message._no_save = True
if item.get("_turn_continuation"):
message._turn_continuation = True
messages.append(message)

return messages
Expand All @@ -279,18 +283,20 @@ def load_messages(history: list[dict]) -> list[Message]:
def dump_messages(
messages: list[Message], *, include_temporary: bool = False
) -> list[dict]:
"""Serialize working messages with optional temporary-content markers.
"""Serialize working messages with turn boundaries and optional exclusions.
Args:
messages: Runtime working messages.
include_temporary: Preserve exclusion markers for the event journal.
Returns:
Serialized messages with optional temporary-content markers.
Serialized messages retaining turn boundaries and optional exclusions.
"""
dumped: list[dict] = []
for message in messages:
message_data = message.model_dump()
if message._turn_continuation:
message_data["_turn_continuation"] = True
if include_temporary and message._no_save:
message_data["_no_save"] = True
if isinstance(message.content, list):
Expand Down
14 changes: 7 additions & 7 deletions astrbot/core/agent/runners/tool_loop_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -1503,10 +1503,10 @@ async def _step_until_done(
if self.req:
self.req.func_tool = None
self.run_context.tools = None
# 注入提示词
await self._append_context_messages(
[Message(role="user", content=self.MAX_STEPS_REACHED_PROMPT)]
)
# Keep the generated instruction in the active user turn.
limit_message = Message(role="user", content=self.MAX_STEPS_REACHED_PROMPT)
limit_message._turn_continuation = True
await self._append_context_messages([limit_message])
# 再执行最后一步
async with aclosing(self.step()) as responses:
async for resp in responses:
Expand Down Expand Up @@ -1630,9 +1630,9 @@ async def append_tool_result_images(
if content is not None:
content.extend(image_parts)
else:
await self._append_context_messages(
[Message(role="user", content=image_parts)]
)
image_message = Message(role="user", content=image_parts)
image_message._turn_continuation = True
await self._append_context_messages([image_message])
logger.debug(
f"Appended {len(cached_images)} cached image(s) to context for LLM review"
)
Expand Down
8 changes: 1 addition & 7 deletions astrbot/core/astr_agent_runtime/delegated_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,13 +415,7 @@ async def _prepare_turn(
)
req = ProviderRequest(
system_prompt=instructions.system_prompt,
contexts=[
{
**message.model_dump(),
**({"_no_save": True} if message._no_save else {}),
}
for message in history
],
contexts=dump_messages(history, include_temporary=True),
func_tool=tools if tools.tools else None,
conversation=Conversation(
platform_id=caller.event.get_platform_id(),
Expand Down
4 changes: 4 additions & 0 deletions astrbot/core/provider/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ def _ensure_message_to_dicts(
for message in messages:
if isinstance(message, Message):
dicts.append(message.model_dump())
elif "_turn_continuation" in message:
dicts.append(
{k: v for k, v in message.items() if k != "_turn_continuation"}
)
else:
dicts.append(message)

Expand Down
49 changes: 49 additions & 0 deletions tests/agent/test_context_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,36 @@ async def test_fallback_keeps_latest_round_when_it_alone_exceeds_limit(
assert result == [messages[0], messages[-1]]
assert "only the latest round left" in caplog.text

@pytest.mark.asyncio
@pytest.mark.parametrize("summary", [False, True])
async def test_token_fallback_keeps_internal_notice_with_oversized_request(
self, summary
):
"""The last internal notice cannot replace the active request in fallback."""
from astrbot.core.agent.message import dump_messages, load_messages

original = self._rounds_with_tool_chain("f" * 900)
messages = load_messages(
dump_messages(original)
+ [
{"role": "assistant", "content": "Working"},
{
"role": "user",
"content": "Internal notice",
"_turn_continuation": True,
},
]
)
config = ContextConfig(
max_context_tokens=1000,
llm_compress_provider=FailingProvider() if summary else None,
custom_token_counter=CharTokenCounter(),
)

result = await ContextManager(config).process(messages)

assert result == [messages[0], *messages[-3:]]

@pytest.mark.asyncio
@pytest.mark.parametrize("summary", [False, True])
@pytest.mark.parametrize("custom_counter", [False, True])
Expand Down Expand Up @@ -1228,6 +1258,25 @@ def test_split_rounds_empty(self):
rounds = split_into_rounds([])
assert len(rounds) == 0

@pytest.mark.parametrize("as_models", [False, True])
def test_split_rounds_keeps_internal_user_messages_in_current_round(
self, as_models
):
"""Internal notices must not split a user's request from its result."""
from astrbot.core.agent.context.round_utils import split_into_rounds
from astrbot.core.agent.message import load_messages

history = [
{"role": "user", "content": "Request"},
{"role": "assistant", "content": "Working"},
{"role": "user", "content": "Internal notice", "_turn_continuation": True},
{"role": "assistant", "content": "Done"},
{"role": "user", "content": "Follow-up"},
]
messages = load_messages(history) if as_models else history

assert split_into_rounds(messages) == [messages[:4], messages[4:]]

def test_split_rounds_accepts_message_objects(self):
"""Message objects can be split without converting them to dictionaries."""
from astrbot.core.agent.context.round_utils import split_into_rounds
Expand Down
Loading
Loading