iflytek/astron-agent · error · RequestValidationError

messages role order must alternate between user and…

Error message

messages role order must alternate between user and assistant

What it means

validate_messages_params enforces that roles strictly alternate user/assistant. When messages[i].role does not equal the expected next_role (starting from user and flipping each step), it raises RequestValidationError with loc body.messages[i].role and msg "messages role order must alternate between user and assistant".

Solutions

  1. Merge consecutive same-role messages into one message (concatenate content) before sending.
  2. Ensure the array starts with a user message and alternates strictly.
  3. Insert a minimal assistant acknowledgment between consecutive user turns if merging is not possible.
  4. Client-side, run the same alternation check on the history and normalize it before the request.

Example fix

# before
messages = [
  {"role": "user", "content": "a"},
  {"role": "user", "content": "b"},
]

# after
messages = [{"role": "user", "content": "a\nb"}]  # or alternate with assistant
Defensive patterns

Strategy: validation

Validate before calling

def normalize_alternating(messages):
    out = []
    for m in messages:
        if out and out[-1]["role"] == m["role"]:
            out[-1]["content"] += "\n" + m["content"]
        else:
            out.append(dict(m))
    return out

Type guard

def is_alternating(messages) -> bool:
    expected = "user"
    for m in messages:
        if m.get("role") != expected:
            return False
        expected = "assistant" if expected == "user" else "user"
    return True

Try / catch

try:
    r = client.post(url, json={"messages": messages})
    r.raise_for_status()
except httpx.HTTPStatusError as e:
    if 'must alternate' in e.response.text:
        messages = normalize_alternating(messages)
        r = client.post(url, json={"messages": messages})

Prevention

When it happens

Trigger: Sending consecutive messages of the same role (two user messages in a row, or two assistant messages), or starting the array with an assistant message when the validator expects the first role to be user.

Common situations: Clients appending multiple user turns from retries or multi-input UIs; chat histories imported from other systems that allow consecutive same-role turns; branching regeneration code that duplicates assistant replies.

Understand the failure class

Background: "Invalid ... format", "must be in format X", "does not look like a ..." — invalid argument format errors across CLI tools and libraries — this error's family across 17 libraries.

Related errors


AI-assisted analysis of iflytek/astron-agent@5e758547a8 (2026-09-12). Data as JSON: /api/errors/9de13ec26227b0bc. Report an issue: GitHub.

Appendix: source

Thrown at core/agent/api/schemas/base_inputs.py:67

                        }
                    ]
                )

            if message.get("role") == "system":
                # System role not supported
                raise RequestValidationError(
                    errors=[
                        {
                            "type": "literal_error",
                            "loc": ("body", "messages", i, "role"),
                            "msg": "'role' must be user or assistant",
                        }
                    ]
                )

            if message.get("role") != next_role:
                # Wrong order
                raise RequestValidationError(
                    errors=[
                        {
                            "type": "literal_error",
                            "loc": ("body", "messages", i, "role"),
                            "msg": (
                                "messages role order must alternate "
                                "between user and assistant"
                            ),
                        }
                    ]
                )

            next_role = "assistant" if next_role == "user" else "user"

        if next_role != "assistant":
            # Last message is not user
            raise RequestValidationError(
                errors=[

View on GitHub (pinned to 5e758547a8)