fix(loop): do not execute a tool call cut off by the output limit (#2719)

json-repair was closing the partial arguments and the tool then ran, so a
write could persist half a value and report success. A truncated round now
keeps the text and records one not-executed result per call.

Fixes #2713

Signed-off-by: fanjiahe <fanjiahe@mail.ustc.edu.cn>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
CyanPersica
2026-11-30 14:18:06 +08:00
committed by GitHub
parent 9ec5815df5
commit b061e71d9b
5 changed files with 195 additions and 12 deletions

View File

@@ -171,7 +171,7 @@ notices:
loop_budget_exhausted: "Exploration budget reached; answering with what has been gathered."
loop_settlement: "Exploration budget reached; completing required follow-up before the final answer."
output_truncated: "The model output reached its token limit; asked it to continue."
tool_call_truncated: "The model reached its output token limit while writing a tool call, so the call may be incomplete. If this repeats, raise this capability's max tokens or pick a model that reasons less."
tool_call_truncated: "The model reached its output token limit while writing a tool call. The call was not executed. If this repeats, raise this capability's max tokens or pick a model that reasons less."
loop_error_finish: "A step failed ({error}); answering with what has been gathered."
provider_retry: "The model provider connection was interrupted; retrying."
provider_unavailable: "Unable to reach the model provider. Please retry."

View File

@@ -127,7 +127,7 @@ notices:
loop_budget_exhausted: "探索轮次预算已用尽,将基于已收集的材料作答。"
loop_settlement: "探索轮次预算已用尽;正在完成必要收尾,然后给出最终回答。"
output_truncated: "模型输出达到 token 上限,已要求其继续完成回答。"
tool_call_truncated: "模型在生成工具调用时达到输出 token 上限,该调用可能不完整。若反复出现,请提高该能力的最大输出 token,或改用推理更短的模型。"
tool_call_truncated: "模型在生成工具调用时达到输出 token 上限,该调用未执行。若反复出现,请提高该能力的最大输出 token,或改用推理更短的模型。"
loop_error_finish: "某一步执行失败({error}),将基于已收集的材料作答。"
provider_retry: "模型服务连接中断,正在重试。"
provider_unavailable: "无法连接模型服务,请重试。"

View File

@@ -6,6 +6,7 @@ It runs inside the originating Python task to preserve account/workspace scopes.
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from deeptutor.runtime.agentic.messages import (
@@ -372,6 +373,50 @@ class AgentLoopHost:
),
)
async def _refuse_truncated_tool_calls(self, result: values.LLMCallResult) -> DispatchOutcome:
"""Tell the model each call in a cut-off round was not executed.
Display parsing uses the stdlib decoder only. A partial value is never
repaired and never passed to a tool.
"""
notice = (
"Model output was truncated. No tools in this batch were executed; "
"retry with complete arguments."
)
tool_messages: list[dict[str, Any]] = []
for call in result.tool_calls:
name = str(call.get("name") or "")
raw = call.get("arguments") or ""
parsed: Any
try:
parsed = json.loads(raw) if isinstance(raw, str) else raw
except json.JSONDecodeError:
parsed = None
display = parsed if isinstance(parsed, dict) else {"arguments": raw}
await self.stream.tool_call(
tool_name=name,
args=display,
source=self.loop.source,
stage=self.loop.stage,
metadata={"trace_kind": "tool_call", "truncated": True},
)
await self.stream.tool_result(
tool_name=name,
result=notice,
source=self.loop.source,
stage=self.loop.stage,
metadata={"trace_kind": "tool_result", "truncated": True},
)
tool_messages.append(
{
"role": "tool",
"tool_call_id": call.get("id") or "",
"name": name,
"content": notice,
}
)
return DispatchOutcome(tool_messages=tool_messages)
async def dispatch_tools(self) -> dict[str, bool]:
result = self.result
assert result is not None
@@ -379,9 +424,9 @@ class AgentLoopHost:
await self.warning(
"notices.tool_call_truncated",
(
"The model reached its output token limit while writing a tool call, so the call "
"may be incomplete. If this repeats, raise this capability's max tokens or pick "
"a model that reasons less."
"The model reached its output token limit while writing a tool call. "
"The call was not executed. If this repeats, raise this capability's "
"max tokens or pick a model that reasons less."
),
)
tool_names = tuple(str(call.get("name") or "") for call in result.tool_calls)
@@ -404,13 +449,18 @@ class AgentLoopHost:
if provider_state is not None:
assistant["_provider_response_state"] = provider_state
self.messages.append(assistant)
self.dispatch = await self.pipeline._dispatch_tool_calls(
tool_calls=result.tool_calls,
context=self.context,
stream=self.stream,
iteration_index=self.state.tool_steps,
stage=self.loop.stage,
)
if finish_was_truncated(result.finish_reason):
# json-repair would close a cut-off argument string, and a write
# tool would then persist that half value. Refuse the whole batch.
self.dispatch = await self._refuse_truncated_tool_calls(result)
else:
self.dispatch = await self.pipeline._dispatch_tool_calls(
tool_calls=result.tool_calls,
context=self.context,
stream=self.stream,
iteration_index=self.state.tool_steps,
stage=self.loop.stage,
)
self.state.sources.extend(self.dispatch.sources)
self.messages.extend(self.dispatch.tool_messages)
extend_transient_model_messages(

View File

View File

@@ -0,0 +1,133 @@
"""A tool call cut off by the output limit must not run."""
from __future__ import annotations
import pytest
from deeptutor.agents.loop.loop_host import AgentLoopHost
from deeptutor.agents.loop.loop_state import AgentLoopState, LLMCallResult
from deeptutor.runtime.agentic.tool_dispatch import DispatchOutcome
_CUT_OFF = '{"note": "Calculus/Week 7", "content": "## Integration\\n- take u'
class _Stream:
def __init__(self) -> None:
self.events: list[tuple[str, str, object]] = []
async def progress(self, message: str, **_kwargs: object) -> None:
self.events.append(("progress", message, None))
async def tool_call(self, tool_name: str, args: dict, **_kwargs: object) -> None:
self.events.append(("tool_call", tool_name, args))
async def tool_result(self, tool_name: str, result: str, **_kwargs: object) -> None:
self.events.append(("tool_result", tool_name, result))
class _Pipeline:
loop_max_tokens = 100
dispatched: list[list[dict]]
def __init__(self) -> None:
self.dispatched = []
def _t(self, _key: str, default: str = "") -> str:
return default
def _capability_tool_round_output_policy(self, _context, _text: str, _names: tuple) -> str:
return ""
async def _dispatch_tool_calls(self, **kwargs: object) -> DispatchOutcome:
self.dispatched.append(list(kwargs["tool_calls"])) # type: ignore[arg-type]
return DispatchOutcome(
tool_messages=[
{
"role": "tool",
"tool_call_id": "call_1",
"name": "obsidian_append",
"content": '{"status": "appended"}',
}
]
)
class _Loop:
source = "chat"
stage = "exploring"
context = None
def __init__(self, pipeline: _Pipeline, stream: _Stream) -> None:
self.pipeline = pipeline
self.stream = stream
self._transient_model_messages: list[dict] = []
def _clean(self, text: str) -> str:
return text
async def _release_deferred_output(self, _result: LLMCallResult) -> None:
return None
async def _discard_deferred_output(self, _result: LLMCallResult) -> None:
return None
def _host(finish_reason: str) -> tuple[AgentLoopHost, _Pipeline, _Stream]:
pipeline = _Pipeline()
stream = _Stream()
loop = _Loop(pipeline, stream)
host = AgentLoopHost(loop, [], AgentLoopState(), 0) # type: ignore[arg-type]
host.result = LLMCallResult(
text="Appending the note.",
visible_text="Appending the note.",
finish_reason=finish_reason,
tool_calls=[
{
"id": "call_1",
"name": "obsidian_append",
"arguments": _CUT_OFF,
}
],
)
return host, pipeline, stream
@pytest.mark.asyncio
async def test_truncated_tool_call_is_not_executed() -> None:
host, pipeline, stream = _host("length")
outcome = await host.dispatch_tools()
assert outcome == {"pause": False}
assert pipeline.dispatched == []
assert host.dispatch is not None
assert host.dispatch.tool_messages == [
{
"role": "tool",
"tool_call_id": "call_1",
"name": "obsidian_append",
"content": (
"Model output was truncated. No tools in this batch were executed; "
"retry with complete arguments."
),
}
]
assert [message["role"] for message in host.messages] == ["assistant", "tool"]
assert host.messages[0]["tool_calls"][0]["function"]["arguments"] == _CUT_OFF
assert stream.events[0][0] == "progress"
assert "not executed" in str(stream.events[0][1])
assert stream.events[1] == ("tool_call", "obsidian_append", {"arguments": _CUT_OFF})
assert stream.events[2][0] == "tool_result"
assert "were executed" in str(stream.events[2][2])
@pytest.mark.asyncio
async def test_complete_tool_call_still_dispatches() -> None:
host, pipeline, _stream = _host("stop")
outcome = await host.dispatch_tools()
assert outcome == {"pause": False}
assert pipeline.dispatched == [host.result.tool_calls] # type: ignore[union-attr]
assert host.dispatch is not None
assert host.dispatch.tool_messages[0]["content"] == '{"status": "appended"}'