Skip to content

feat(core): 阻止长度截断的不完整工具调用执行并引导模型分块恢复 - #2649

Closed
CyberXavier wants to merge 3 commits into
agentscope-ai:mainfrom
CyberXavier:fix/openai-compatible-length-truncated-tool-calls
Closed

CyberXavier wants to merge 3 commits into
agentscope-ai:mainfrom
CyberXavier:fix/openai-compatible-length-truncated-tool-calls

Conversation

@CyberXavier

Copy link
Copy Markdown
Contributor

fix:#2648
本 PR 修复 OpenAI 兼容模型因输出长度限制截断工具参数后,工具调用失败、遗留 pending 状态或重复重试同一大调用的问题。

主要改动:

  • 透传 OpenAI 兼容响应的 finish_reason,覆盖流式与非流式响应。
  • 将终止原因写入最终 AssistantMessage 元数据及 ModelCallEndEvent。
  • 工具参数聚合仍保留非法 JSON 降级为 {} 的原有兼容行为。
  • 对非空但无法组成合法 JSON 对象的原始工具参数增加内部不完整标记。
  • 仅在 finish_reason=length 且工具参数不完整时阻止实际工具执行。
  • 返回与原始 ToolUse 具有相同 toolCallId 和工具名的错误 ToolResult,避免遗留 pending tool call。
  • 错误 ToolResult 明确要求模型不要原样重试,而应缩小参数并通过多次小调用或可用的增量更新工具完成任务,支持大文件采用首段创建加后续追加/编辑的方式恢复。
  • 完整参数、非 length 终止原因及缺失终止原因的响应保持原有执行与降级行为。

测试覆盖:

  • 流式与非流式 finish_reason=length 解析;
  • 完整及不完整工具参数聚合;
  • 截断参数不执行实际工具;
  • 错误 ToolResult 的恢复指令;
  • AgentState 中 ToolUse 与同 ID ToolResult 的端到端配对。

修复后运行效果:
image

- 在 MessageMetadataKeys 中新增 MODEL_FINISH_REASON 常量用于存储模型完成原因
- 扩展 ModelCallEndEvent 类以包含 finishReason 字段
- 在 OpenAI 扩展中添加测试用例验证流式和非流式响应的完成原因保留
- 修改 ReActAgent 中的事件发射逻辑以传递上下文中的完成原因
- 在 ReasoningContext 中添加 finishReason 字段并处理分块响应中的完成原因
- 实现长度限制工具调用标记功能,在模型达到输出长度限制时标记不完整工具调用
- 在 ToolCallsAccumulator 中检测原始内容完整性并在元数据中标记不完整内容
- 更新 ToolExecutor 阻止具有长度限制不完整参数的工具调用执行
- 添加新的元数据键用于标识原始内容不完整和输出长度限制状态
- 新增 ReActAgentLengthLimitedToolCallTest 测试类验证完整的长度截断工具调用流程
@codecov

codecov Bot commented Aug 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.00000% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...scope/core/agent/accumulator/ReasoningContext.java 87.50% 1 Missing and 2 partials ⚠️
...va/io/agentscope/core/event/ModelCallEndEvent.java 83.33% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@CyberXavier

Copy link
Copy Markdown
Contributor Author

@jujn 您好,这个pr需要您帮忙审批一下

@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/agent Agent runtime, pipeline, hooks, plan area/core/model Model providers and formatters area/core/tool Tool, skill, RAG abstractions labels Aug 11, 2026
@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with the main branch and cannot be merged. Please rebase or merge main into your branch and resolve the conflicts:

git fetch origin
git checkout fix/openai-compatible-length-truncated-tool-calls
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a re-review once the conflicts are resolved.


Automated notification by github-manager-bot

@oss-maintainer oss-maintainer left a comment

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.

Summary

PR #2649 blocks execution of tool calls whose arguments were truncated by an output-length limit (finish_reason="length" + non-parseable raw argument JSON), returning a same-ID error ToolResult that guides the model to retry with smaller calls; the mechanism is correct and well tested for OpenAI-compatible models, but the guard only recognizes the literal "length" reason, leaving other bundled providers unprotected.

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ReasoningContext.java:168 — The guard matches only the literal finish reason "length" while living in core. Other bundled extensions report length limits differently: Gemini maps candidate.finishMessage() (values like MAX_TOKENS), openai-official Responses API sets finishReason to the response status ("completed"/"incomplete"), and Anthropic never maps stop_reason. Truncated tool calls from those providers still silently execute with the "{}" fallback. Normalize length-limit reasons in the model layer or match a set ({"length", "max_tokens", "MAX_TOKENS"}) so the guard is provider-agnostic.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java:194 — Rebase note: the diff is based on the old single-arg executeCore(ToolCallParam); main has refactored it to executeCore(param, requestConfig, internalChunkCallback) with resolveTool() and an external-tool suspension short-circuit, and the branch currently conflicts with main. Keep the guard at the top of the new executeCore so a truncated external/HITL tool call returns the error result instead of being suspended.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ReasoningContext.java:224 — Test gap: no coverage for the early-return branch (complete tool call under finish_reason=length stays executable) or for a mixed response with one complete and one truncated call; likely part of the 4 uncovered lines Codecov reported.

Suggestions

  • Verified safe, no action needed: ToolUseBlock.getMetadata() never returns null (null becomes emptyMap), so the new metadata lookups cannot NPE; ReasoningContext is created fresh per reasoning round, so no stale finishReason leaks across iterations; the blocked error result gets its ID/name via withIdAndName in executeWithInfrastructure, preserving pending-tool-call pairing in AgentState; the legacy 2-arg ModelCallEndEvent constructor is retained (delegating), and RemoteEventCodec disables FAIL_ON_UNKNOWN_PROPERTIES, so wire/JSON compatibility holds; internal metadata markers (_raw_content_incomplete, _output_length_limit) are not sent back to providers since formatters read only specific keys (thoughtSignature, cacheControl) and rebuild args via resolveToolCallArgsJson; no extra JSON parsing was introduced (the isValidJsonObject call was already there and is now reused).
  • The e2e test's recovery guidance relies on the model obeying the error message; the ReAct maxIters bound already guarantees termination if it retries unchanged, so no loop risk.

Automated review by github-manager-bot


// Add all tool calls
List<ToolUseBlock> toolCalls = toolCallsAcc.buildAllToolCalls();
if (FINISH_REASON_LENGTH.equals(finishReason)) {

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.

The truncation guard keys on the literal finish reason "length", but the check lives in core while other bundled model extensions report length limits with different values: GeminiResponseParser maps candidate.finishMessage() (Gemini's finish reasons are e.g. MAX_TOKENS), ResponsesResponseParser (openai-official) sets finishReason to the response status ("completed"/"incomplete"), and the Anthropic extension never maps stop_reason at all. For those providers a truncated tool call still silently falls back to "{}" arguments and is executed, so the new safety guard only protects OpenAI-chat-completions-style endpoints. Consider normalizing length-limit reasons in the model layer (or matching a set such as {"length", "max_tokens", "MAX_TOKENS"}) so the ToolExecutor guard is provider-agnostic instead of OpenAI-specific.

// potentially destructive side effects is invoked from a truncated argument stream. The
// error result is returned through the normal execution path, which preserves the tool
// call ID and prevents the ReAct state from retaining an unmatched pending tool call.
if (Boolean.TRUE.equals(

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.

Rebase note: this diff is based on the old single-arg executeCore(ToolCallParam); current main has refactored it to executeCore(param, requestConfig, internalChunkCallback) with resolveTool() and an external-tool suspension short-circuit (ToolResultBlock.suspended on main), and the branch currently conflicts with main. When rebasing, keep this guard at the very top of the new executeCore so a length-truncated external/HITL tool call returns the error result instead of being suspended with "{}" arguments.

if (!Boolean.TRUE.equals(
toolCall.getMetadata()
.get(ToolUseBlock.METADATA_RAW_CONTENT_INCOMPLETE))) {
return toolCall;

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.

Test gap: the early-return branch (a complete tool call inside a finish_reason=length response must stay executable) has no coverage, nor does a mixed response containing one complete and one truncated call in the same response. These pin the most subtle guarantee of this change (only the affected call is blocked; complete calls in the same response still run) and are likely among the 4 uncovered lines Codecov reported. A small ReasoningContextTest case with one valid-args ToolUseBlock plus one truncated block under finishReason("length") would cover both.

@oss-maintainer oss-maintainer left a comment

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.

Summary

PR #2649 blocks execution of tool calls whose arguments were truncated by an output-length limit (finish_reason="length" + non-parseable raw argument JSON), returning a same-ID error ToolResult that guides the model to retry with smaller calls; the mechanism is correct and well tested for OpenAI-compatible models, but the guard only recognizes the literal "length" reason, leaving other bundled providers unprotected.

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ReasoningContext.java:168 — The guard matches only the literal finish reason "length" while living in core. Other bundled extensions report length limits differently: Gemini maps candidate.finishMessage() (values like MAX_TOKENS), openai-official Responses API sets finishReason to the response status ("completed"/"incomplete"), and Anthropic never maps stop_reason. Truncated tool calls from those providers still silently execute with the "{}" fallback. Normalize length-limit reasons in the model layer or match a set ({"length", "max_tokens", "MAX_TOKENS"}) so the guard is provider-agnostic.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java:194 — Rebase note: the diff is based on the old single-arg executeCore(ToolCallParam); main has refactored it to executeCore(param, requestConfig, internalChunkCallback) with resolveTool() and an external-tool suspension short-circuit, and the branch currently conflicts with main. Keep the guard at the top of the new executeCore so a truncated external/HITL tool call returns the error result instead of being suspended.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ReasoningContext.java:224 — Test gap: no coverage for the early-return branch (complete tool call under finish_reason=length stays executable) or for a mixed response with one complete and one truncated call; likely part of the 4 uncovered lines Codecov reported.

Suggestions

  • Verified safe, no action needed: ToolUseBlock.getMetadata() never returns null (null becomes emptyMap), so the new metadata lookups cannot NPE; ReasoningContext is created fresh per reasoning round, so no stale finishReason leaks across iterations; the blocked error result gets its ID/name via withIdAndName in executeWithInfrastructure, preserving pending-tool-call pairing in AgentState; the legacy 2-arg ModelCallEndEvent constructor is retained (delegating), and RemoteEventCodec disables FAIL_ON_UNKNOWN_PROPERTIES, so wire/JSON compatibility holds; internal metadata markers (_raw_content_incomplete, _output_length_limit) are not sent back to providers since formatters read only specific keys (thoughtSignature, cacheControl) and rebuild args via resolveToolCallArgsJson; no extra JSON parsing was introduced (the isValidJsonObject call was already there and is now reused).
  • The e2e test's recovery guidance relies on the model obeying the error message; the ReAct maxIters bound already guarantees termination if it retries unchanged, so no loop risk.

Automated review by github-manager-bot


// Add all tool calls
List<ToolUseBlock> toolCalls = toolCallsAcc.buildAllToolCalls();
if (FINISH_REASON_LENGTH.equals(finishReason)) {

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.

The truncation guard keys on the literal finish reason "length", but the check lives in core while other bundled model extensions report length limits with different values: GeminiResponseParser maps candidate.finishMessage() (Gemini's finish reasons are e.g. MAX_TOKENS), ResponsesResponseParser (openai-official) sets finishReason to the response status ("completed"/"incomplete"), and the Anthropic extension never maps stop_reason at all. For those providers a truncated tool call still silently falls back to "{}" arguments and is executed, so the new safety guard only protects OpenAI-chat-completions-style endpoints. Consider normalizing length-limit reasons in the model layer (or matching a set such as {"length", "max_tokens", "MAX_TOKENS"}) so the ToolExecutor guard is provider-agnostic instead of OpenAI-specific.

// potentially destructive side effects is invoked from a truncated argument stream. The
// error result is returned through the normal execution path, which preserves the tool
// call ID and prevents the ReAct state from retaining an unmatched pending tool call.
if (Boolean.TRUE.equals(

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.

Rebase note: this diff is based on the old single-arg executeCore(ToolCallParam); current main has refactored it to executeCore(param, requestConfig, internalChunkCallback) with resolveTool() and an external-tool suspension short-circuit (ToolResultBlock.suspended on main), and the branch currently conflicts with main. When rebasing, keep this guard at the very top of the new executeCore so a length-truncated external/HITL tool call returns the error result instead of being suspended with "{}" arguments.

if (!Boolean.TRUE.equals(
toolCall.getMetadata()
.get(ToolUseBlock.METADATA_RAW_CONTENT_INCOMPLETE))) {
return toolCall;

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.

Test gap: the early-return branch (a complete tool call inside a finish_reason=length response must stay executable) has no coverage, nor does a mixed response containing one complete and one truncated call in the same response. These pin the most subtle guarantee of this change (only the affected call is blocked; complete calls in the same response still run) and are likely among the 4 uncovered lines Codecov reported. A small ReasoningContextTest case with one valid-args ToolUseBlock plus one truncated block under finishReason("length") would cover both.

@oss-maintainer oss-maintainer left a comment

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.

Summary

Re-review of the latest push. The truncation-guard feature itself is reasonable, but the branch is significantly stale against origin/main: the refactors in ToolExecutor.executeCore and ReasoningContext server-tool placement are now in main, so this diff is both in conflict and semantically regressive as-is. Please rebase onto latest main and re-verify the two critical integration points below, then this can be re-reviewed. The PR is currently unmergeable due to conflicts with main.

Findings

  • [CRITICAL] agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java:267 — The executeCore(ToolCallParam) signature and the toolRegistry.getTool(toolCall.getName()) lookup below are stale relative to origin/main. Current main uses executeCore(ToolCallParam, ToolRequestConfig, BiConsumer<ToolUseBlock, ToolResultBlock>) and resolveTool(toolCall.getName(), requestConfig) to support per-request tool overrides and external-tool short-circuiting. Merging this diff without rebasing will conflict with that refactor and risks reintroducing the pre-refactor code path.
  • [CRITICAL] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ReasoningContext.java:69 — This hunk keeps blocks.addAll(toolCalls) in the final message, but origin/main has changed this line to blocks.addAll(serverToolResults.placeAfterToolCalls(toolCalls)) to correctly interleave provider server-tool results. The length-limit marker should be applied to toolCalls before passing them to serverToolResults.placeAfterToolCalls(toolCalls), not by dropping the placement logic.

Automated review by github-manager-bot, re-review at af0c351

@ben1226q

Copy link
Copy Markdown

@CyberXavier 你的这个pr他们怎么一直没合啊。我也碰到这个问题呢

@CyberXavier

Copy link
Copy Markdown
Contributor Author

@CyberXavier 你的这个pr他们怎么一直没合啊。我也碰到这个问题呢

这个pr我稍后会关闭,这里你可以通过其他方式引导agent(例如增加系统提示词),如果在框架层面直接引导模型这样不太好。

@ben1226q

Copy link
Copy Markdown

@CyberXavier 但是如果不把 finish_reason=length 具体原因传出来,我怎么知道该不该续写呢?能给点提示吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/agent Agent runtime, pipeline, hooks, plan area/core/model Model providers and formatters area/core/tool Tool, skill, RAG abstractions enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants