Repository navigation
Description
Describe the bug
在 fallback 结构化输出路径中,如果模型在同一个 assistant 响应里同时返回业务工具调用和 generate_response,首次调用可以成功返回结构化结果,业务工具也正常执行,但后续清理会删除整条 assistant 消息,连同业务 tool_use 一起删除,而业务 tool_result 仍留在会话中。
这会破坏工具调用与结果的配对,并把损坏的历史传给下一轮模型请求。显式使用 InMemoryAgentStateStore 时,读回的状态也存在相同问题。
To Reproduce
不需要真实模型、网络或 API key。使用下面的 JUnit 本地假模型测试:
- 通过
Model默认能力走 syntheticgenerate_response路径。 - 注册真实 Java 工具
recordAction,并记录其调用次数。 - 假模型在一条 ChatResponse 中返回
recordAction(id=business)与generate_response(id=format),后者参数为{"response":{"status":"ok"}}。 - 执行
agent.call(input, Receipt.class),确认结构化结果为status=ok且业务工具执行一次。 - 检查清理后的历史:
business的 tool_use 不存在,tool_result 却仍存在。
分两轮返回上述两个调用则正常;同轮返回时,交换调用顺序仍复现。默认状态和显式状态存储都复现。
将下方测试放到 agentscope-core/src/test/java/io/agentscope/core/agent/StructuredMixedBatchAuditTest.java 后,从仓库根目录运行:
mvn -B -T1C -pl agentscope-core -am test -Dtest=StructuredMixedBatchAuditTest -Dsurefire.failIfNoSpecifiedTests=false完整复现测试:同批次两种顺序、分轮对照,以及状态存储对照
/*
* Copyright 2024-2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.agentscope.core.agent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.message.ContentBlock;
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.TextBlock;
import io.agentscope.core.message.ToolResultBlock;
import io.agentscope.core.message.ToolUseBlock;
import io.agentscope.core.message.UserMessage;
import io.agentscope.core.model.ChatResponse;
import io.agentscope.core.model.GenerateOptions;
import io.agentscope.core.model.Model;
import io.agentscope.core.model.ToolSchema;
import io.agentscope.core.state.AgentState;
import io.agentscope.core.state.InMemoryAgentStateStore;
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.Toolkit;
import io.agentscope.core.util.JsonUtils;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import reactor.core.publisher.Flux;
/** Checks that structured-output cleanup preserves unrelated tool-use/result pairs. */
class StructuredMixedBatchAuditTest {
public static class Receipt {
public String status;
}
public static class BusinessTools {
final AtomicInteger calls = new AtomicInteger();
@Tool(description = "Record an action")
public String recordAction() {
calls.incrementAndGet();
return "receipt";
}
}
@ParameterizedTest
@CsvSource({
"separate-rounds,false",
"business-first,false",
"structured-first,false",
"separate-rounds,true",
"business-first,true",
"structured-first,true"
})
void structuredCleanupMustPreserveBusinessCall(String order, boolean persisted) {
AtomicInteger modelCalls = new AtomicInteger();
BusinessTools business = new BusinessTools();
Toolkit toolkit = new Toolkit();
toolkit.registerTool(business);
Model model =
new Model() {
@Override
public String getModelName() {
return "local-mixed-batch";
}
@Override
public Flux<ChatResponse> stream(
List<Msg> messages, List<ToolSchema> tools, GenerateOptions options) {
int n = modelCalls.incrementAndGet();
boolean structured =
tools.stream()
.anyMatch(t -> "generate_response".equals(t.getName()));
if (!structured) {
Set<String> callIds = callIds(messages);
Set<String> orphanResults = new HashSet<>(resultIds(messages));
orphanResults.removeAll(callIds);
if (!orphanResults.isEmpty()) {
return Flux.error(
new IllegalArgumentException(
"fixture provider rejects tool_result without"
+ " tool_use: "
+ orphanResults));
}
return Flux.just(
response(List.of(TextBlock.builder().text("next ok").build())));
}
ToolUseBlock action = tool("business", "recordAction", Map.of());
ToolUseBlock format =
tool(
"format",
"generate_response",
Map.of("response", Map.of("status", "ok")));
if ("separate-rounds".equals(order)) {
return Flux.just(response(List.of(n == 1 ? action : format)));
}
return Flux.just(
response(
"business-first".equals(order)
? List.of(action, format)
: List.of(format, action)));
}
};
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
RuntimeContext rc =
RuntimeContext.builder().userId("audit-user").sessionId("audit-session").build();
ReActAgent.Builder builder =
ReActAgent.builder()
.name("audit")
.sysPrompt("record then format")
.model(model)
.toolkit(toolkit);
if (persisted) builder.stateStore(store);
ReActAgent agent = builder.build();
Msg first =
agent.call(
List.of(new UserMessage("Record once and return JSON")),
Receipt.class,
rc)
.block(Duration.ofSeconds(10));
assertNotNull(first);
assertEquals("ok", first.getStructuredData(Receipt.class).status);
assertEquals(1, business.calls.get());
List<Msg> history =
persisted
? store.get("audit-user", "audit-session", "agent_state", AgentState.class)
.orElseThrow()
.getContext()
: agent.getAgentState(rc).getContext();
System.out.printf(
"MIXED order=%s persisted=%s remainingCalls=%s remainingResults=%s%n",
order, persisted, callIds(history), resultIds(history));
Msg next = agent.call("Next question", rc).block(Duration.ofSeconds(10));
assertEquals("next ok", next.getTextContent());
assertEquals(Set.of("business"), callIds(history));
assertEquals(Set.of("business"), resultIds(history));
}
private static Set<String> callIds(List<Msg> messages) {
return messages.stream()
.flatMap(m -> m.getContentBlocks(ToolUseBlock.class).stream())
.map(ToolUseBlock::getId)
.collect(Collectors.toSet());
}
private static Set<String> resultIds(List<Msg> messages) {
return messages.stream()
.flatMap(m -> m.getContentBlocks(ToolResultBlock.class).stream())
.map(ToolResultBlock::getId)
.collect(Collectors.toSet());
}
private static ToolUseBlock tool(String id, String name, Map<String, Object> input) {
return ToolUseBlock.builder()
.id(id)
.name(name)
.input(input)
.content(JsonUtils.getJsonCodec().toJson(input))
.build();
}
private static ChatResponse response(List<ContentBlock> blocks) {
return ChatResponse.builder().id("reply").content(blocks).build();
}
}Expected behavior
清理框架内部的结构化输出工具时,保留业务工具调用及其配对结果。后续请求不能收到孤立 tool_result,也不应残留没有结果的 synthetic tool_use。
Error messages / observed state
order=separate-rounds persisted=false remainingCalls=[business] remainingResults=[business]
order=business-first persisted=false remainingCalls=[] remainingResults=[business]
order=structured-first persisted=false remainingCalls=[] remainingResults=[business]
order=separate-rounds persisted=true remainingCalls=[business] remainingResults=[business]
order=business-first persisted=true remainingCalls=[] remainingResults=[business]
order=structured-first persisted=true remainingCalls=[] remainingResults=[business]
6 个场景中,两个分轮对照通过,四个同批次场景在下一轮被假模型的配对检查拒绝。独立重跑结果一致。
注意:fixture provider rejects tool_result without tool_use: [business] 是测试中的显式检查,不是真实厂商 API 的报错。这里直接验证的是会话历史的配对损坏。
Environment
- AgentScope-Java:
2.1.0-SNAPSHOT - 已验证 commit:
5baff2613401bf87b3a967b185f2f14945ec594e - Java: Microsoft OpenJDK 21.0.7
- OS: macOS
Additional context / root cause
ReActAgent.java 的清理逻辑 按整条消息过滤。isStructuredOutputRelated 在任意 tool_use 名称为 generate_response 时返回 true,导致同一条消息中的业务 tool_use 被一起删除。业务结果则因名称不是 generate_response 而保留。
dispatchToolCalls 已显式支持同批次 synthetic 与普通工具,问题发生在执行后的上下文清理,不是工具未执行。
建议仅对混合消息做内容块级清理,保留业务调用/结果配对,纯结构化输出消息沿用现有清理行为;不改变工具调度、权限或 native fallback。分类函数同时被 usage/thinking 提取复用,需要避免连带改变这些行为。
我愿意提交一个聚焦这条配对不变量的修复及回归测试。如果已有相关工作,请告知,避免重复。
Activity
fix(core): 保留结构化输出混合批次中的业务工具历史 (agentscope-ai#4086)
Merge upstream main and resolve structured-output cleanup conflict
fix(core): preserve business tool-use/result pairs in structured-outp…