spring-projects / spring-projects/spring-ai

Chat memory advisor causes message ordering problem with default system message prompt

Open
#4,170 20 comments 2 reactions 1 assignee View on GitHub

@sunyuhan1998 is already working on this.

Since Sep 10, 2025.

status: waiting-for-triage
Dominant language
Java
Stars
9.5k
Forks
2.9k
Avg merge
1d 7h
Merged PRs (30d)
6

Description

Bug description

Using MessageChatMemoryAdvisor with a default system prompt causes "conversation roles must alternate user/assistant/user/assistant" error. This appears to be the same issue as reported in #2216 which was marked as fixed in 1.0.0-M8 but can be reproduced in 1.0.1.

Environment

  • Spring AI version: 1.0.1
  • Spring Boot version: 3.5.4
  • Java version: 21.0.2
  • AI Provider: OpenAI (Docker Model Runner with ai/mistral:latest model for testing)
  • Dependencies: spring-ai-starter-model-chat-memory, spring-ai-starter-model-openai

Steps to reproduce

  1. Create a ChatClient with defaultSystem() prompt and MessageChatMemoryAdvisor configured
  2. Make a chat call with a conversation id
  3. Attempt a second chat call with the same conversation id
  4. The second call fails with error "After the optional system message, conversation roles must alternate user/assistant/user/assistant..."

The error occurs during the second chatClient.prompt().call().content() call. Upon debugging the MessageChatMemoryAdvisor#before, I can see that messages are collected in the wrong order:

  1. UserMessage
  2. AssistantMessage
  3. SystemMessage
  4. UserMessage

Expected behavior

The MessageChatMemoryAdvisor should properly order the system prompt and conversation context to allow for continued dialogue with alternating user/assistant roles without errors.

I would expect messages to be collected in the following order instead which I believe should allow the request to succeed:

  1. SystemMessage
  2. UserMessage
  3. AssistantMessage
  4. UserMessage

Minimal Complete Reproducible example

https://github.com/sjohnr/spring-ai-chat-memory-bug

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.