Troubleshooting Message Order Conflicts When Connecting Reasoning Models to Agent Frameworks

    This article explains how to diagnose and resolve "message order conflict" errors that occur when an agent framework connects to a reasoning-capable language model through a compatible chat interface. It covers common causes such as incorrect placement of reasoning content, missing tool-call pairs, invalid role sequences, mishandled empty content, and inconsistent conversation history. It also provides a pre-integration checklist, a smoke-test script, and a message‑structure validation script to help identify the root cause quickly.

    1. Conclusion and Applicability

    When reasoning mode is enabled, the server rejects the entire request from the very first call with a “message order conflict” error. In most cases, the problem lies in the structure of the messages array assembled by the framework, not in the model itself. The model is not involved in this validation step, so the troubleshooting should focus on how the request is built.

    This article applies to agent frameworks that connect to a reasoning model through a chat-compatible interface. If your provider uses a different protocol, consult their specific documentation. Note that reasoning‑related field names, allowed roles, and return‑related rules differ between providers. The field names and examples shown here only illustrate the structure; always replace them with the actual values from your provider’s documentation and your framework’s configuration.

    2. Pre-Integration Checklist

    2.1 Prepare Credentials

    Create an API key on the model service platform. Store it in environment variables or a secret management service, never in configuration files, code repositories, or logs. Rotate keys regularly and use separate keys for different applications.

    1. export MODEL_API_KEY="<your-api-key>"

    2.2 Confirm the API Protocol

    Most providers offer endpoints compatible with mainstream chat interfaces. Before integration, verify three things: the request path, the supported message roles, and whether reasoning content is returned in a separate field.

    Role types are the most common source of issues. Some interfaces do not recognize the developer role; in such cases, switch to system. The name of the reasoning field also varies by provider. Do not hardcode based on experience — check the provider’s interface documentation directly.

    2.3 Write the Framework Configuration

    Configuration structures differ across frameworks. The example below only shows the fields you need to fill in. Replace baseUrl, api, model id, contextWindow, and maxTokens with actual values from the provider’s documentation, and adjust field names according to your framework’s documentation.

    1. {
    2. "provider": {
    3. "baseUrl": "https://<provider-host>/<compatible-path>",
    4. "apiKey": "${MODEL_API_KEY}",
    5. "api": "<protocol type>",
    6. "models": [
    7. {
    8. "id": "<model-id>",
    9. "reasoning": true,
    10. "contextWindow": 131072,
    11. "maxTokens": 32768
    12. }
    13. ]
    14. },
    15. "defaults": {
    16. "model": "<provider>/<model-id>"
    17. }
    18. }

    contextWindow and maxTokens must be taken from the provider’s documentation. If you set values exceeding the model’s actual limits, two typical behaviors occur: the request returns an error, or the server silently truncates the output. When an error is returned, the response body or framework logs usually contain phrases like “context length” or “max_tokens”, which help determine if the limit is exceeded.

    2.4 Smoke Test

    After configuration, verify the end‑to‑end link with a minimal request. The script below tests both a non‑reasoning request and a reasoning request. The reasoning‑enabling parameters are passed via the environment variable REASONING_EXTRA; the field names again follow your provider’s documentation. The script captures HTTP errors and prints the status code and response body, making it easy to distinguish network, authentication, and message‑structure problems.

    1. import json
    2. import os
    3. import sys
    4. import urllib.error
    5. import urllib.request
    6. URL = "https://<provider-host>/<compatible-path>/chat/completions"
    7. MODEL = "<model-id>"
    8. # Extra parameters to enable reasoning mode; empty for non‑reasoning test
    9. REASONING_EXTRA = json.loads(os.environ.get("REASONING_EXTRA", "{}"))
    10. PROMPT = [{"role": "user", "content": "Reply with two words: connected"}]
    11. def call(messages, extra=None):
    12. payload = {"model": MODEL, "messages": messages}
    13. if extra:
    14. payload.update(extra)
    15. req = urllib.request.Request(
    16. URL,
    17. data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    18. headers={
    19. "Content-Type": "application/json",
    20. "Authorization": "Bearer " + os.environ["MODEL_API_KEY"],
    21. },
    22. )
    23. try:
    24. with urllib.request.urlopen(req, timeout=60) as resp:
    25. return json.load(resp)
    26. except urllib.error.HTTPError as e:
    27. body = e.read().decode("utf-8", errors="replace")
    28. print(f"HTTP {e.code}: {body[:500]}", file=sys.stderr)
    29. raise
    30. except urllib.error.URLError as e:
    31. print(f"Network error: {e.reason}", file=sys.stderr)
    32. raise
    33. if __name__ == "__main__":
    34. body = call(PROMPT)
    35. print("Non‑reasoning:", body["choices"][0]["message"]["content"])
    36. if REASONING_EXTRA:
    37. body = call(PROMPT, REASONING_EXTRA)
    38. msg = body["choices"][0]["message"]
    39. print("Reasoning:", msg.get("content"))
    40. print("Returned fields:", sorted(msg.keys()))

    How to interpret the results:

    • If both tests fail, the issue is likely at the HTTP/endpoint level — check the URL, API key, model name, or permissions (steps 2.1 and 2.2).
    • If both tests succeed but the framework still reports errors, the problem is probably in the framework’s session handling. In that case, debug the conversation logic directly rather than repeatedly modifying the endpoint.

    3. Message Order Conflicts in Reasoning Mode

    3.1 First Check if It’s a History Problem

    After configuration, you may get a “message order conflict” on the very first message, with a suggestion to start a new conversation. Some users clear the session files, but the error persists.

    If the error appears even after starting a new session, the problem is not in historical records. The first request has an empty history, so the error must come from the framework’s logic for assembling each request. The framework may be inserting the system prompt, role templates, or cached content into messages, and the order or roles of these entries violate the server’s rules.

    3.2 Five Common Causes

    Message order conflicts typically stem from one of the following five causes. The table summarizes the symptoms, triggers, and fastest way to diagnose each. A detailed explanation follows.

    Cause Typical Symptom Trigger Condition Fastest Diagnosis
    Reasoning content placed incorrectly Error from the second turn onward; first turn is fine When reasoning is enabled, assistant messages get longer Check whether the assistant’s content contains reasoning text
    Missing tool‑call pairing Error after a tool call Timeout, interruption, or only partial results saved Verify that each tool_call_id matches a preceding tool_calls id
    Invalid role sequence Error after switching providers Role name not recognized, or extra messages inserted Print only the role sequence and inspect it row by row
    Empty content mishandled Error when calling a tool after reasoning content stored as empty string, None, or string "None" Inspect the actual JSON form of content in the request body
    Inconsistent history saving Error after multiple turns or when toggling reasoning on/off Some turns save reasoning, others don’t Compare the session archive structure across turns

    1. Reasoning content placed incorrectly. The framework might concatenate reasoning text into content, or save the reasoning content as a separate assistant message. The two incorrect forms are shown below.

    Correct: keep reasoning in the provider‑specific field, with content containing only the final reply. Replace <reasoning_field> with the actual field name from your provider:

    1. {"role": "assistant", "content": "Final reply text", "<reasoning_field>": "Reasoning process text"}

    Incorrect: appending reasoning to content, or inserting a separate assistant message for reasoning:

    1. {"role": "assistant", "content": "<think>Reasoning process text</think>Final reply text"}
    2. {"role": "assistant", "content": "Reasoning process text"}

    To diagnose, print the messages array and check whether the content of each assistant message contains reasoning text or thought tags. If the provider requires reasoning content to be sent back, preserve the separate field. If the provider forbids sending it back, remove that field entirely — do not merge it into content.

    2. Missing pairing between assistant and tool messages. The assistant initiates a tool call, but the corresponding tool message is missing, or the tool_call_id in the tool message does not match any of the tool_calls ids. Example:

    1. {"role": "assistant", "content": null, "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "search", "arguments": "{}"}}]}
    2. {"role": "tool", "tool_call_id": "call_2", "content": "Search result"}

    The tool message references call_2, while the tool call list contains only call_1 — the server will reject this request. To diagnose, list every tool_calls id and verify that each subsequent tool message references one of those ids. The script in section 3.3 automates this check.

    3. Invalid role sequence. Typical problems: the server does not recognize a certain role name, there are two consecutive assistant messages, or a tool message appears without a preceding assistant that contains tool_calls. Example of an invalid sequence:

    1. ["system", "developer", "user", "assistant", "assistant", "tool"]

    Here, developer may not be recognized, two consecutive assistant messages are often rejected, and tool lacks the necessary preceding assistant with tool_calls. To diagnose, print only the role sequence and check the order line by line. This problem often occurs after switching providers or when the framework inserts extra messages.

    4. Empty content mishandled. When an assistant message contains only tool calls and no text, content may be empty or null. Providers accept different representations — some accept null, others require an empty string. The most common error is serializing an empty value into the string "None". To diagnose, print the raw JSON before sending the request and check the actual form of the empty value. If the framework saves empty values but fails to serialize them correctly, the validation may fail.

    5. Inconsistent history saving. Within the same session, some turns may have reasoning content saved, others not. Context truncation or compression can also break the history structure. To diagnose, compare the session archive across turns and verify structural consistency. Section 4 gives handling methods.

    Whether reasoning content should be sent back depends on the provider. Some providers require reasoning to be returned in multi‑turn tool calls; others explicitly forbid it. This article does not make that decision for you — follow the provider’s API documentation.

    3.3 Message‑Structure Validation Script

    The following script reads raw request messages (e.g., saved from the framework’s debug log) and checks them for common structural issues. It validates role sequences, assistant–tool pairing, and the presence of the reasoning field when needed.

    1. import json
    2. import sys
    3. def validate_messages(messages):
    4. errors = []
    5. prev_role = None
    6. # For tool pairing
    7. known_tool_ids = set()
    8. for i, msg in enumerate(messages):
    9. role = msg.get("role")
    10. if not role:
    11. errors.append(f"Message {i}: missing role")
    12. continue
    13. if prev_role == "assistant" and role == "assistant":
    14. errors.append(f"Message {i}: two consecutive assistant messages")
    15. if role == "tool":
    16. tid = msg.get("tool_call_id")
    17. if tid not in known_tool_ids:
    18. errors.append(f"Message {i}: tool_call_id '{tid}' not matched")
    19. if role == "assistant":
    20. tool_calls = msg.get("tool_calls")
    21. if tool_calls:
    22. for tc in tool_calls:
    23. known_tool_ids.add(tc.get("id"))
    24. content = msg.get("content")
    25. if isinstance(content, str) and ("<think>" in content or "reasoning" in content.lower()):
    26. errors.append(f"Message {i}: content may contain reasoning text")
    27. prev_role = role
    28. return errors
    29. if __name__ == "__main__":
    30. path = sys.argv[1] if len(sys.argv) > 1 else "messages.json"
    31. with open(path) as f:
    32. data = json.load(f)
    33. errs = validate_messages(data)
    34. if errs:
    35. print("Validation failed:")
    36. for e in errs:
    37. print(" -", e)
    38. else:
    39. print("Validation passed")

    Save the message list that the framework sends (for example, by enabling debug logging) into a JSON file and run the script against it. This catches structural problems before you investigate deeper integration logic.

    4. Handling Strategies Once the Cause Is Identified

    After identifying the specific cause, apply the corresponding fix:

    • For reasoning content placement: move reasoning text to the dedicated field (or remove it entirely if the provider disallows it). Ensure content contains only the final answer.
    • For missing tool‑call pairing: ensure every assistant tool_calls id has a matching tool message with the same tool_call_id. If a tool call timed out or the result was lost, either retry the tool call or drop the incomplete assistant message from the history.
    • For invalid role sequences: rewrite the conversation history to conform to the provider’s allowed roles and order. Typically, system/developer may appear only at the beginning, then alternating user and assistant, with tool messages immediately following the assistant that made the call.
    • For empty content: explicitly set content to an empty string ("") or null according to the provider’s specification. Ensure your serialization does not turn empty values into the string "None".
    • For inconsistent history saving: apply a uniform policy for all turns — either always keep the reasoning field or always strip it, depending on the provider’s requirement. After any context truncation or compression, re‑validate the message structure before sending.

    If the framework uses its own session cache or database, you may need to clear the affected session after making these changes. However, as noted earlier, if the error occurs on the very first request with an empty history, the fix must be in the request‑assembly logic, not in the stored session.

    5. Final Checks

    After correcting the message structure, rerun the smoke test from section 2.4. If both non‑reasoning and reasoning requests succeed at the API level, plug the corrected messages into the framework’s debug log and verify that the framework now sends structurally valid requests. Keep the validation script (section 3.3) handy for future iterations, especially when you upgrade the framework or switch to a different reasoning model provider.

    Remember: every provider has its own conventions for reasoning fields, role names, and return rules. Always refer to the official documentation of both the model provider and your agent framework for the exact field names and permitted message patterns.