TokenLimitedChatCompletionContext can orphan a FunctionExecutionResultMessage mid-list when truncating
Description
TokenLimitedChatCompletionContext.get_messages() truncates by repeatedly popping the message at len(messages) // 2 until the token budget is satisfied, then does a single cleanup check for a leftover FunctionExecutionResultMessage at index 0. If the middle-index pop removes an AssistantMessage that contains FunctionCalls while its paired FunctionExecutionResultMessage sits elsewhere in the list (not at index 0), the result is never repaired: the returned message list has a tool result with no matching tool call anywhere in it.
Code: python/packages/autogen-core/src/autogen_core/model_context/_token_limited_chat_completion_context.py, lines 57-77.
while token_count > self._token_limit and len(messages) > 0:
middle_index = len(messages) // 2
messages.pop(middle_index)
token_count = self._model_client.count_tokens(messages, tools=self._tool_schema)
...
if messages and isinstance(messages[0], FunctionExecutionResultMessage):
# Handle the first message is a function call result message.
messages = messages[1:]The same pattern exists in the token_limit is None branch a few lines above (uses remaining_tokens instead of count_tokens).
Reproduction
import asyncio
from autogen_core import FunctionCall
from autogen_core.model_context import TokenLimitedChatCompletionContext
from autogen_core.models import (
AssistantMessage,
FunctionExecutionResult,
FunctionExecutionResultMessage,
UserMessage,
)
class FakeCounter:
def count_tokens(self, messages, tools=None):
return len(messages) # one "token" per message, for a deterministic repro
async def main():
ctx = TokenLimitedChatCompletionContext(model_client=FakeCounter(), token_limit=6)
messages = [
UserMessage(content="m0", source="user"),
UserMessage(content="m1", source="user"),
UserMessage(content="m2", source="user"),
AssistantMessage(content=[FunctionCall(id="call_1", arguments="{}", name="tool")], source="assistant"),
FunctionExecutionResultMessage(
content=[FunctionExecutionResult(content="ok", name="tool", call_id="call_1")]
),
UserMessage(content="m5", source="user"),
UserMessage(content="m6", source="user"),
]
for m in messages:
await ctx.add_message(m)
result = await ctx.get_messages()
print([type(m).__name__ for m in result])
asyncio.run(main())With 7 messages and token_limit=6, exactly one pop is needed: middle_index = 7 // 2 = 3, which removes the AssistantMessage holding call_1. The loop then stops (6 messages, count_tokens returns 6, not greater than 6). The post-loop check only looks at index 0, which is a UserMessage, so nothing gets fixed. The returned list still contains the FunctionExecutionResultMessage for call_1 with no corresponding AssistantMessage/FunctionCall anywhere in it.
Expected behavior
get_messages() should never return a FunctionExecutionResultMessage that does not have a matching preceding tool call in the same returned list, since that list is sent directly to the model client as-is (see call sites in _assistant_agent.py).
Actual behavior
An orphaned FunctionExecutionResultMessage can appear anywhere in the truncated list, not just index 0. Providers that validate the tool_call_id/tool_result pairing (OpenAI, Anthropic) reject this with a 400-style error at request time, so the failure only surfaces once a conversation has grown long enough to trigger truncation with a tool call sitting near the middle of the buffer, which makes it awkward to reproduce from the failing request alone.
Notes
The existing test test_token_limited_model_context_openai_with_function_result (autogen-core/tests/test_model_context.py) only covers the case where the leftover result already happens to land at index 0 after the pop, so it does not exercise the mid-list case above.
Which packages were used, and which versions?
autogen-core, main branch, commit 027ecf0a379bcc1d09956d46d12d44a3ad9cee14.
Source: microsoft/autogen