Skip to content

[Feature]: Improve AutoContextMemory strategy control, async compression flow, and system prompt preservation #1350

Closed

Description

@Atlas4285

AgentScope-Java is an open-source project. To involve a broader community, we recommend asking your questions in English.

Is your feature request related to a problem? Please describe.

While integrating and extending AutoContextMemory behavior, I found several limitations in the current implementation:

  1. Compression strategies cannot be independently enabled or disabled.
  2. Compression internally uses model.stream(...).block(), which breaks the reactive chain and makes compression effectively synchronous.
  3. AutoContextHook only preserves the first SYSTEM message when rebuilding inputMessages, causing additional system prompts to be discarded.

These issues reduce flexibility, increase latency under heavy compression scenarios, and may unexpectedly lose important system-level instructions.

Describe the solution you'd like

1. Add per-strategy enable/disable switches in AutoContextConfig

Allow each compression strategy to be configured independently, for example:

strategy1Enabled
strategy2Enabled
......

This would make it easier to:

  • experiment with different compression strategies,
  • selectively disable expensive strategies,
  • customize compression behavior for different applications.

2. Make compression fully asynchronous

Current implementation uses patterns similar to:

model.stream(...)
    ...
    .block();

inside AutoContextMemory.

This breaks the reactive execution model and turns compression into a synchronous operation.

In practice, when multiple historical rounds need summarization, compression latency increases significantly because each summary blocks sequentially.

Suggested improvement:

  • expose async compression APIs returning Mono<Msg> / Flux<Msg>,
  • keep the entire compression pipeline reactive,
  • avoid .block() inside memory compression logic.

This would allow:

  • concurrent summarization,
  • better scalability,
  • lower latency during heavy context compression.

3. Preserve all SYSTEM messages in AutoContextHook

Current implementation only preserves the first SYSTEM message when rebuilding inputMessages:

// line 235-236 in io.agentscope.core.memory.autocontext
if (!originalInputMessages.isEmpty()
        && originalInputMessages.get(0).getRole() == MsgRole.SYSTEM)

As a result, additional SYSTEM messages are discarded.

This can cause issues in scenarios involving:

  • layered system prompts,
  • middleware-injected prompts,
  • safety prompts,
  • RAG system instructions,
  • MCP/tool framework system injections.

Suggested improvement:

  • preserve all existing SYSTEM messages instead of only the first one.

Describe alternatives you've considered

Currently, these issues can be worked around by:

  • implementing custom hooks,
  • manually rebuilding inputMessages,
  • using reflection to replace internal memory storage,

However, these approaches are difficult to maintain and duplicate internal logic already present in AutoContextMemory.

Additional contextAdditional context

Example of fully asynchronous implementation:

private Mono<Boolean> summaryPreviousRoundMessages(List<Msg> rawMessages) {
    if (rawMessages == null || rawMessages.isEmpty()) {
        return Mono.just(false);
    }

    int latestAssistantIndex = -1;
    for (int i = rawMessages.size() - 1; i >= 0; i--) {
        Msg msg = rawMessages.get(i);
        if (MsgUtils.isFinalAssistantResponse(msg)) {
            latestAssistantIndex = i;
            break;
        }
    }

    if (latestAssistantIndex < 0) {
        return Mono.just(false);
    }

    List<SummaryTask> tasks = new ArrayList<>();
    int currentUserIndex = -1;

    for (int i = 0; i < latestAssistantIndex; i++) {
        Msg msg = rawMessages.get(i);

        if (msg.getRole() == MsgRole.USER) {
            currentUserIndex = i;
            continue;
        }

        if (!MsgUtils.isFinalAssistantResponse(msg) || currentUserIndex < 0) {
            continue;
        }

        int userIndex = currentUserIndex;
        int assistantIndex = i;

        currentUserIndex = -1;

        if (assistantIndex - userIndex == 1) {
            continue;
        }

        int startIndex = userIndex + 1;
        int endIndex = assistantIndex;

        List<Msg> messagesToSummarize = new ArrayList<>();
        messagesToSummarize.add(rawMessages.get(userIndex));
        messagesToSummarize.addAll(rawMessages.subList(startIndex, endIndex + 1));

        tasks.add(new SummaryTask(
                userIndex,
                startIndex,
                endIndex,
                messagesToSummarize));
    }

    if (tasks.isEmpty()) {
        return Mono.just(false);
    }

    int concurrency = Math.min(tasks.size(), 5);

    List<Mono<SummaryResult>> summaryMonos = new ArrayList<>();

    for (SummaryTask task : tasks) {

        Mono<SummaryResult> mono =
                summaryPreviousRoundConversation(task.messagesToSummarize())
                        .filter(summaryMsg -> {
                            String content = summaryMsg.getTextContent();
                            return content != null && !content.trim().isEmpty();
                        })
                        .map(summaryMsg -> new SummaryResult(
                                task.userIndex(),
                                task.startIndex(),
                                task.endIndex(),
                                summaryMsg));

        summaryMonos.add(mono);
    }

    return Flux.fromIterable(summaryMonos)
            .flatMap(mono -> mono, concurrency)
            .collectList()
            .map(results -> {

                if (results == null || results.isEmpty()) {
                    return false;
                }

                results.sort((a, b) ->
                        Integer.compare(b.startIndex(), a.startIndex()));

                for (SummaryResult result : results) {

                    rawMessages.subList(
                            result.startIndex(),
                            result.endIndex() + 1)
                            .clear();

                    int insertIndex = result.userIndex() + 1;

                    rawMessages.add(insertIndex, result.summaryMsg());
                }

                return true;
            });
}

private Mono<Msg> summaryPreviousRoundConversation(List<Msg> messages) {

    List<Msg> newMessages = new ArrayList<>();

    String previousRoundSummaryPrompt =
            PromptProvider.getPreviousRoundSummaryPrompt(null);

    newMessages.add(
            Msg.builder()
                    .role(MsgRole.SYSTEM)
                    .content(TextBlock.builder()
                            .text(previousRoundSummaryPrompt)
                            .build())
                    .build());

    String prompt = buildSummaryPreviousRoundPrompt(messages);

    newMessages.add(
            Msg.builder()
                    .role(MsgRole.USER)
                    .content(TextBlock.builder()
                            .text(prompt)
                            .build())
                    .build());

    Model model = createModel(userId, modelName);

    ReasoningContext context =
            new ReasoningContext("conversation_summary");

    return model.stream(newMessages, null, null)
            .concatMap(chunk -> processChunk(chunk, context))
            .then(Mono.defer(() ->
                    Mono.just(context.buildFinalMessage())))
            .map(block -> {

                Map<String, Object> metadata = new HashMap<>();

                if (block != null && block.getChatUsage() != null) {
                    metadata.put(
                            MessageMetadataKeys.CHAT_USAGE,
                            block.getChatUsage());
                }

                String summaryContent =
                        block != null ? block.getTextContent() : "";

                return Msg.builder()
                        .role(MsgRole.ASSISTANT)
                        .name("assistant")
                        .content(TextBlock.builder()
                                .text(summaryContent)
                                .build())
                        .metadata(metadata)
                        .build();
            })
            .onErrorResume(e -> Mono.empty());
}

Example of preserving all SYSTEM messages instead of only the first one:

List<Msg> newInputMessages = new ArrayList<>();

for (Msg msg : event.getInputMessages()) {
    if (msg.getRole() == MsgRole.SYSTEM) {
        newInputMessages.add(msg);
    }
}

newInputMessages.addAll(autoContextMemory.getMessages());

event.setInputMessages(newInputMessages);

Activity

  1. added
    enhancement
    on May 7, 2026
  2. BEASTSHRIRAM commented on May 11, 2026

    @BEASTSHRIRAM
    Contributor

    @LearningGp Could you assign me this?

  3. added
    area/ext/memory
    on May 28, 2026
  4. BEASTSHRIRAM commented on May 28, 2026

    @BEASTSHRIRAM
    Contributor

    Hey @LearningGp i have implemented the fix, could you take a look at PR #1523 when you get a chance? Would appreciate a review. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/ext/memoryenhancement

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions