fix(core): guard orphan tool messages in dialogue serialization

The intent REQLLM path (core/handle/intentHandler.py) records a tool result via
`Message(role="tool", content=text)` with no tool_call_id and no preceding
assistant tool_calls. `Dialogue.getMessages` serializes it as a function_response
anyway. When that history is later replayed to an OpenAI-compatible endpoint,
the endpoint derives `function_response.name` by matching the tool_call_id back
to a function_call; with no match the name is empty.

gemini-2.5-flash tolerated the empty name, but gemini-3.5-flash rejects the whole
request with HTTP 400 "GenerateContentRequest.contents[N].parts[0]
.function_response.name: Name cannot be empty", so every affected turn falls back
to "Sorry, the system is busy now." Only tool-using sessions and only the chat
turns that replay the accumulated tool results were affected.

Guard at the serialization boundary in `getMessages`: emit a role="tool" message
as a function_response only when a preceding assistant message carries a matching
tool_call id; otherwise demote it to a plain assistant context line so the turn
survives. Valid tool-call pairs — including empty-string ids that still match —
are unchanged. This defends against any orphan source, not just the intent path.

Adds self-contained regression tests (no conftest required).
This commit is contained in:
Brad Shannon 2026-07-14 16:09:00 -04:00
parent 1998807b69
commit 31cc365fcd
2 changed files with 126 additions and 8 deletions

View file

@ -35,18 +35,44 @@ class Dialogue:
if m.tool_calls is not None:
dialogue.append({"role": m.role, "tool_calls": m.tool_calls})
elif m.role == "tool":
dialogue.append(
{
"role": m.role,
"tool_call_id": (
str(uuid.uuid4()) if m.tool_call_id is None else m.tool_call_id
),
"content": m.content,
}
tool_call_id = (
str(uuid.uuid4()) if m.tool_call_id is None else m.tool_call_id
)
# A tool/function_response message is only valid when a preceding
# assistant message issued a matching tool_call. Some paths (e.g. the
# intent REQLLM handler) inject a bare tool result with no matching
# tool_call; replaying that to Gemini's OpenAI-compat endpoint yields
# HTTP 400 "function_response.name: Name cannot be empty" (gemini-3.5
# rejects it; gemini-2.5 tolerated it). Demote such orphans to a plain
# assistant context message so the turn survives.
if self._has_matching_tool_call(tool_call_id, dialogue):
dialogue.append(
{
"role": m.role,
"tool_call_id": tool_call_id,
"content": m.content,
}
)
else:
dialogue.append({"role": "assistant", "content": m.content})
else:
dialogue.append({"role": m.role, "content": m.content})
@staticmethod
def _has_matching_tool_call(tool_call_id, dialogue):
"""True if an already-serialized assistant message carries a tool_call
whose id equals ``tool_call_id``. Handles dict- and object-shaped
tool_calls."""
for entry in reversed(dialogue):
tool_calls = entry.get("tool_calls") if isinstance(entry, dict) else None
if not tool_calls:
continue
for tc in tool_calls:
tc_id = tc.get("id") if isinstance(tc, dict) else getattr(tc, "id", None)
if tc_id == tool_call_id:
return True
return False
def get_llm_dialogue(self) -> List[Dict[str, str]]:
# 直接调用get_llm_dialogue_with_memory,传入None作为memory_str
# 这样确保说话人功能在所有调用路径下都生效

View file

@ -0,0 +1,92 @@
"""Regression tests for the orphan tool-message guard in ``Dialogue.getMessages``.
A ``role="tool"`` message is only valid when a preceding assistant message issued
a matching ``tool_call`` (correlated by id). Some paths (e.g. the intent REQLLM
handler in ``core/handle/intentHandler.py``) inject a bare tool result via
``Message(role="tool", content=text)`` with no ``tool_call_id`` and no preceding
assistant ``tool_calls``. When that dialogue is later replayed to an OpenAI-compat
LLM endpoint, the endpoint derives ``function_response.name`` by matching the
``tool_call_id`` back to a ``function_call``; with no match the name is empty.
``gemini-2.5-flash`` tolerated it, but ``gemini-3.5-flash`` rejects the whole
request with HTTP 400 ``function_response.name: Name cannot be empty``, dropping
the turn to the "system is busy" fallback.
The fix demotes such orphans to a plain assistant context line while leaving valid
tool-call pairs (including empty-string ids that still match) untouched.
Self-contained: ``Dialogue`` has no heavy dependencies, so no conftest required.
"""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from core.utils.dialogue import Dialogue, Message # noqa: E402
def _serialize(messages):
d = Dialogue()
for m in messages:
d.put(m)
return d.get_llm_dialogue_with_memory(None, None)
def test_orphan_tool_message_is_demoted():
# Mirrors the intent REQLLM path: a bare tool result with no matching tool_call.
out = _serialize(
[
Message(role="user", content="turn on the light"),
Message(role="tool", content="ok"),
Message(role="user", content="anything else?"),
]
)
# The orphan must NOT be emitted as a tool/function_response...
assert all(m.get("role") != "tool" for m in out), out
# ...but its content must be preserved (demoted, not dropped).
assert any(m.get("content") == "ok" for m in out), out
def test_valid_tool_pair_is_preserved():
# An assistant tool_call followed by its matching tool result stays a function_response.
out = _serialize(
[
Message(role="user", content="turn on the light"),
Message(
role="assistant",
tool_calls=[
{
"id": "call_1",
"type": "function",
"function": {"name": "set_light", "arguments": "{}"},
}
],
),
Message(role="tool", tool_call_id="call_1", content="ok"),
]
)
assert any(
m.get("role") == "tool" and m.get("tool_call_id") == "call_1" for m in out
), out
def test_empty_string_ids_still_match():
# OpenAI-compat streaming can yield empty tool-call ids; an empty id on both the
# assistant tool_call and the tool result still correlates and must be preserved.
out = _serialize(
[
Message(role="user", content="x"),
Message(
role="assistant",
tool_calls=[
{
"id": "",
"type": "function",
"function": {"name": "f", "arguments": "{}"},
}
],
),
Message(role="tool", tool_call_id="", content="ok"),
]
)
assert any(m.get("role") == "tool" for m in out), out