fix(provider): recover trailing assistant message as user to prevent empty request

When a subagent result is injected with current_role="assistant",
_enforce_role_alternation drops the trailing assistant message, leaving
only the system prompt. Providers like Zhipu/GLM reject such requests
with error 1214 ("messages parameter invalid"). Now the last popped
assistant message is recovered as a user message when no user/tool
messages remain.
This commit is contained in:
chengyongru
2026-04-13 12:01:45 +08:00
committed by chengyongru
parent 62bd54ac4a
commit 89ea2375fd
2 changed files with 56 additions and 1 deletions
+15 -1
View File
@@ -392,8 +392,22 @@ class LLMProvider(ABC):
else:
merged.append(dict(msg))
last_popped = None
while merged and merged[-1].get("role") == "assistant":
merged.pop()
last_popped = merged.pop()
# If removing trailing assistant messages left only system messages,
# the request would be invalid for most providers (e.g. Zhipu/GLM
# error 1214). Recover by converting the last popped assistant
# message to a user message so the LLM can still see the content.
if (
merged
and last_popped is not None
and not any(m.get("role") in ("user", "tool") for m in merged)
):
recovered = dict(last_popped)
recovered["role"] = "user"
merged.append(recovered)
return merged