Skip to content

[Bug]:模型在工具调用前后夹带文本时,TEXT_MESSAGE_START/END 配对错乱,客户端报 "No active text message found with ID" #2988

Closed
1 of 1 issue completed

Description

@Cakulha

[agui] 模型在工具调用前后夹带文本时,TEXT_MESSAGE_START/END 配对错乱,客户端报 "No active text message found with ID"

AgentScope-Java is an open-source project. To involve a broader community, we recommend asking your questions in English.
(以下正文为中文,便于准确描述;如需提交官方仓库建议翻译为英文。)

Describe the bug / 问题描述

在通过 AG-UI 协议(agentscope-extensions-agui)消费 ReActAgent 的事件流时,如果一次 model call 的输出里同时包含「文本」和「工具调用」,且两者交错(典型形态:文本A → 工具调用 → 文本B),客户端会抛出如下错误并中断:

Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '35d04b46134b431c8ceec9b3e78a9f5b'. Start a text message with 'TEXT_MESSAGE_START' first

该报错并非来自 AgentScope 服务端(本仓库代码中检索不到该字符串),而是来自 AG-UI 协议的消费端 SDK(如 CopilotKit / AG-UI runtime 的状态机)。根因在于 AgentScope 的 AG-UI 转换层(AguiStreamContext)对同一个 messageId(即 model call 的 replyId)只发送一次 TEXT_MESSAGE_START / TEXT_MESSAGE_END,而核心层 ReActAgent 的 ModelCallBlockLifecycle 本身是允许「一段文本被 flush 关闭后、工具调用之后再次 start」的。两层语义不一致,导致第二段文本发出时,客户端既找不到匹配的 START、又发现该 ID 已经 END,于是报错。

To Reproduce / 复现步骤

  1. 构造一个 ReActAgent,绑定至少一个工具,并通过 AG-UI 适配器对外暴露(AguiAgentAdapter)。
  2. 让模型在一次回复里输出形如 文本A → 工具调用 → 文本B 的内容(很多模型在 tool-use 响应中会在工具前后夹带 preamble / postscript 文本,属于常见输出形态)。
  3. 用任意 AG-UI 消费端(CopilotKit useCoAgent 等)订阅该 agent 的 SSE 流。
  4. 观察 SSE 事件序列与客户端报错。

触发该 bug 的关键条件:同一次 model call 的 replyId 下,TextBlock 出现了不止一次(被中间的 ToolUseBlock 隔开),且至少两段文本都非空。

用于验证根因的代码位置(基于 2.0.2):

  • 核心层会先把文本 flush 关闭、调用工具后再重新 start:
    • agentscope-core/.../ReActAgent.java ModelCallBlockLifecycle.startText(约 2393 行)使用 textStarted.compareAndSet(false, true),被 flushText(约 2419 行)置回 false 后可以再次 start。
    • startToolCall(约 2406 行)会先调用 flushText,因此工具调用前会发出 TextBlockEndEvent。
  • AG-UI 转换层则假设「一个 messageId = 一段连续文本,只 START/END 一次」:
    • agentscope-extensions-agui/.../adapter/strategy/AguiStreamContext.java startTextMessage(110 行):startedTextMessages 是只增不减的 Set,同一 id 第二次 add 返回 false → 不再重发 TEXT_MESSAGE_START。
    • closeTextMessage(131 行):若 endedTextMessages 已含该 id 则直接 return → 不再重发 TEXT_MESSAGE_END。
    • appendTextDelta(117 行)→ startTextMessage:第二段文本「文本B」到达时,因为该 id 已经 ended,跳过 START,直接发出 TEXT_MESSAGE_CONTENT。

由此客户端实际收到的事件序列为:

TEXT_MESSAGE_START     35d04b46…
TEXT_MESSAGE_CONTENT   35d04b46…  "文本A"
TEXT_MESSAGE_END       35d04b46…
TOOL_CALL_START / TOOL_CALL_END
TEXT_MESSAGE_CONTENT   35d04b46…  "文本B"   ← 缺 START,且该 ID 已 END → 触发报错

Expected behavior / 期望行为

文本A → 工具 → 文本B 的交错输出应被正确映射成客户端可消费的事件序列,不应触发 "No active text message found" 报错。

可能的修复方向(任选其一):

  1. (推荐)将工具之后的文本当作一条新消息:在 appendTextDelta 中,若发现该 messageId 已处于 ended 状态,则派生一个新的 messageId(例如 replyId + "-p2"),重新走完整的 START / CONTENT / END,保证每段不连续文本都是一条独立的 AG-UI 消息。符合 AG-UI「文本消息是单条连续序列」的语义。
  2. 放宽配对约束:允许同一 messageId 多次 START→END→START→END(在 closeTextMessage 后从 startedTextMessages 移除该 id)。但客户端是否接受「同 ID 消息反复 start/end」取决于具体实现,风险更大。

Error messages / 错误信息

Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '35d04b46134b431c8ceec9b3e78a9f5b'. Start a text message with 'TEXT_MESSAGE_START' first

说明:该字符串出自 AG-UI 客户端 SDK,并非 AgentScope 服务端日志。报错里的 32 位十六进制 ID 即为该次 model call 的 replyId(UUID.randomUUID().toString().replace("-",""),见 ReActAgent.java 约 2289 行)。

Environment / 环境信息

  • AgentScope-Java Version: 2.0.2(pom.xml 中 <revision>2.0.2</revision>,HEAD = a5d6213e bump to 2.0.2;该问题在 2.0.1 → 2.0.2 期间相关代码无改动,仍可复现)
  • Java Version: [请补充,例如 17]
  • OS: [请补充,例如 macOS]

Additional context / 补充说明

  • 与「最大迭代次数」无关:初看容易误以为是 MAX_ITERATIONS 触发的摘要(summaryStream,ReActAgent.java 约 3236 行)导致,但摘要使用的是全新的 replyId(约 3304 行),不会复用已结束的 messageId。真正触发条件是「同一 replyId 下文本被工具调用隔开成多段」。轮次越多越容易撞到(统计相关而非因果)。
  • 已核对版本:对比 v2.0.1..v2.0.2,AguiStreamContext.java、核心层 ReActAgent.java 的文本生命周期相关代码(ModelCallBlockLifecycle / flushText 等)均无改动,问题在 2.0.2 依然存在。
  • 快速自证:可在 AguiStreamContext.appendTextDelta(117 行)入口处加一行诊断日志,若命中即可锁定:
    if (delta != null && !delta.isEmpty() && endedTextMessages.contains(messageId)) {
        logger.warn("Re-text on ended messageId={}, delta={}", messageId, delta);
    }
  • 建议附带的复现测试:mock 一个模型,使其在一次 stream 里依次产出 TextBlock("文本A")、ToolUseBlock(...)、TextBlock("文本B"),断言输出的 AG-UI 事件序列里每段非空文本都有匹配的 START/END。

Sub-issues

Sub-issues

1 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. added
    bug
    on Sep 4, 2026
  2. jujn commented on Sep 4, 2026

    @jujn
    Collaborator

    用的哪个模型厂商?agui 模块设计如此,应该在模型层解析响应时,聚合交错的文本

  3. Cakulha commented on Sep 4, 2026

    @Cakulha
    Author

    用的哪个模型厂商?agui 模块设计如此,应该在模型层解析响应时,聚合交错的文本

    OpenAi 接的 Qwen3.8-27B

  4. doctormacky commented on Sep 5, 2026

    @doctormacky

    Qwen3.8-27B 复现了同样的错误。

  5. CryoThrust commented on Sep 5, 2026

    @CryoThrust
    Contributor

    Thanks for the investigation. I agree that the model layer is the better place to normalize this, because AG-UI should receive a stable sequence of assistant text segments rather than infer model-provider-specific interleaving.

    One boundary seems important to make explicit:

    • Text before a tool call and text after the tool result are different semantic segments, even when they belong to the same ReAct iteration.
    • The model adapter can aggregate adjacent TextBlock fragments within one segment, but should not merge text across a ToolUseBlock/tool-result boundary.
    • The normalized event should therefore expose a segment identity (or a new reply/message id per segment), so AG-UI can emit exactly one TEXT_MESSAGE_START and TEXT_MESSAGE_END for each contiguous segment.

    For regression coverage, a provider-independent model response containing TextBlock(A) -> ToolUseBlock -> TextBlock(B) would be useful. The assertion should cover both the normalized core events and the AG-UI event sequence, including cancellation/partial-stream termination. It would also be worth documenting whether the post-tool text is considered a new assistant message segment or a continuation for consumers that render tool traces.

  6. jujn commented on Sep 5, 2026

    @jujn
    Collaborator

    用的哪个模型厂商?agui 模块设计如此,应该在模型层解析响应时,聚合交错的文本

    不好意思,我看成非流式了。大部分模型的回复格式一般为:1Reasoning + 1Text + nToolCall,当时就按这个设计的。一些不太常见的情况下(比如上述)确实会有问题,主要是 AguiStreamContext 状态机太难穷举

  7. CryoThrust commented on Sep 5, 2026

    @CryoThrust
    Contributor

    The state space can stay small if normalization is treated as a segmenter rather than a full ReAct state machine. A minimal provider-independent state is enough:

    IDLE
      TextBlock -> TEXT_OPEN(id), TEXT_DELTA... -> TEXT_OPEN
    TEXT_OPEN
      adjacent TextBlock -> TEXT_DELTA           -> TEXT_OPEN
      ToolUseBlock / ToolResultBlock / terminal -> TEXT_END(id), IDLE
    IDLE
      ToolUseBlock / ToolResultBlock -> emit tool event, IDLE
      terminal -> IDLE
    

    The key invariants are: every TEXT_DELTA has exactly one preceding open segment; every opened segment is closed once on a semantic boundary or terminal/cancellation; and no segment spans a tool-use/tool-result boundary. Tool events do not need to participate in the text state beyond forcing a close.

    That gives a finite parameterized regression matrix instead of trying to enumerate ReAct behavior: text-only, text/tool/text, adjacent text fragments, tool-only, terminal while text is open, cancellation while text is open, and provider chunks split across transport buffers. The model layer can own this normalizer, while AG-UI only serializes the normalized segments. If this direction is accepted, I can prepare the focused tests/implementation slice.

  8. ZHCHJ888 commented on Sep 5, 2026

    @ZHCHJ888
    Contributor

    @jujn 感谢确认,请问前辈我可以尝试修复这个问题吗?我的理解是:同一次 model call 出现 文本A → 工具调用 → 文本B 时,两段文本共用 replyId。AG-UI 将其作为同一个 messageId,第一段结束后,第二段只发 CONTENT 而不再发 START,导致客户端报错。考虑过两种方案:

    1. 核心层:为每个连续文本段生成不同的 blockId,AG-UI 据此生成唯一 messageId。语义更完整,但影响面相对较大。
    2. AG-UI 层:不改核心事件;检测到已结束的 replyId 再次出现文本时,派生新 ID,如 replyId-text-2。改动较小。

    我更倾向于第一种架构更干净,可以请问前辈意见吗?

    不太倾向于简单地从 startedTextMessages / endedTextMessages 中移除原 ID,然后用同一个 messageId 再次发送 START/END,因为不同 AG-UI 客户端不一定允许已经结束的消息 ID 被重新打开

  9. added a commit that references this issue on Sep 9, 2026
    2b378e1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions