Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions agent/moa_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,42 @@ def _render_tool_calls(tool_calls: Any) -> str:
return "\n".join(lines)


def _flatten_content_text(content: Any) -> str:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please reuse agent.message_content.flatten_message_text here rather than adding a second content normalizer. The existing helper already covers Chat/Responses text fields, mapping/object parts, and media filtering; this narrower copy will drift from those supported shapes.

"""Flatten a message ``content`` field to plain text for the advisory view.

``content`` may be a plain string OR a list of content blocks (the
OpenAI/Anthropic multimodal shape, e.g. ``[{"type": "text", "text": ...},
{"type": "image_url", ...}]``) whenever the user attached an image/file or
the turn carries multiple parts. The advisory view is text-only, so we
concatenate every block's text and drop non-text blocks (images, etc.).

Returning ``""`` for a list that carries no text is intentional (a pure
image turn has no advisory text). The bug this fixes: treating ANY
non-string content as ``""`` silently discarded the prompt text of every
content-block message, so references saw an empty turn — tolerated by lax
providers (deepseek, MiniMax) but rejected by strict ones (Z.AI GLM →
``400 未正常接收到prompt参数``), and in both cases the reference lost the
actual instruction. Mirrors the text-extraction pattern used elsewhere in
the codebase (context_compressor, the provider adapters).
"""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for block in content:
if isinstance(block, dict):
text = block.get("text")
if not isinstance(text, str):
# Some shapes nest the string under "content".
text = block.get("content") if isinstance(block.get("content"), str) else None
if isinstance(text, str) and text:
parts.append(text)
elif isinstance(block, str) and block:
parts.append(block)
return "\n".join(parts)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For an image-only user message this returns "", and _reference_messages will still send an empty user turn to the reference. That preserves the strict-provider empty-prompt failure described by this PR for that valid input shape; use a non-empty advisory placeholder or omit the empty turn.

return ""


_ADVISORY_INSTRUCTION = (
"[The conversation above is the current state of the task. Give your "
"most intelligent judgement: what is going on, what should happen next, "
Expand Down Expand Up @@ -470,7 +506,7 @@ def _reference_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
for msg in messages:
role = msg.get("role")
content = msg.get("content")
text = content if isinstance(content, str) else ""
text = _flatten_content_text(content)

if role == "system":
continue
Expand Down Expand Up @@ -517,8 +553,10 @@ def _reference_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
if last_user_content is not None:
return [{"role": "user", "content": last_user_content}]
for msg in reversed(messages):
if msg.get("role") == "user" and isinstance(msg.get("content"), str):
return [{"role": "user", "content": msg["content"]}]
if msg.get("role") == "user":
fallback = _flatten_content_text(msg.get("content"))
if fallback.strip():
return [{"role": "user", "content": fallback}]
return rendered


Expand Down
45 changes: 45 additions & 0 deletions tests/run_agent/test_moa_loop_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,51 @@ def test_reference_messages_fresh_user_turn_ends_on_that_user():
assert view[-1] == {"role": "user", "content": "q2 current"}


def test_reference_messages_flattens_content_blocks_to_text():
"""Multimodal content-block messages must preserve their prompt text.

Regression: a user turn whose ``content`` is a list of blocks (the
OpenAI/Anthropic multimodal shape produced whenever an image/file is
attached) was flattened to "" by the old ``isinstance(content, str) else
''`` guard, silently discarding the instruction. Lax providers tolerated
the empty turn; strict ones (Z.AI GLM) 400'd with "未正常接收到prompt参数".
The advisory view must extract the text blocks and drop non-text ones.
"""
from agent.moa_loop import _reference_messages

messages = [
{"role": "system", "content": "sys"},
{
"role": "user",
"content": [
{"type": "text", "text": "explain binary search"},
{"type": "image_url", "image_url": {"url": "data:..."}},
],
},
]

view = _reference_messages(messages)
# Fresh user turn: preserved, text extracted, image block dropped.
assert view == [{"role": "user", "content": "explain binary search"}]
assert view[-1]["content"].strip(), "prompt text must not be empty"


def test_flatten_content_text_shapes():
"""_flatten_content_text handles str, block lists, image-only, and None."""
from agent.moa_loop import _flatten_content_text

assert _flatten_content_text("hi") == "hi"
assert (
_flatten_content_text(
[{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]
)
== "a\nb"
)
# Image-only content carries no advisory text.
assert _flatten_content_text([{"type": "image_url", "image_url": {"url": "x"}}]) == ""
assert _flatten_content_text(None) == ""


def test_run_reference_prepends_advisory_system_prompt(monkeypatch):
"""Each reference call gets the advisory-role system prompt first.

Expand Down