Skip to content

feat(agent): support structured output in streamEvents - #2919

Merged
jujn merged 6 commits into
agentscope-ai:mainfrom
Letter2025:feat/streamEvents-structured-output
Nov 20, 2026
Merged

jujn merged 6 commits into
agentscope-ai:mainfrom
Letter2025:feat/streamEvents-structured-output

Conversation

@Letter2025

Copy link
Copy Markdown
Contributor

Problem

The fine-grained streaming API (ReActAgent#streamEvents(...)) — the recommended replacement for the deprecated coarse-grained stream(...) — has no structured-output overloads. Only call(msgs, schema/class, ctx) (non-streaming) and the deprecated stream(msgs, options, schema/class, ctx) support outputSchema.

buildAgentStream(...) is private, so downstream code cannot inject a schema variant of streamEvents without forking the framework or relying on the deprecated API (which returns the legacy io.agentscope.core.agent.Event instead of the fine-grained io.agentscope.core.event.AgentEvent).

Closes #1717.

Change

Add the missing fine-grained overloads, reusing the existing buildAgentStream core so streaming and blocking calls share identical lifecycle / middleware / hook semantics:

  • ReActAgent#streamEvents(List<Msg>, Class<?>, RuntimeContext)
  • ReActAgent#streamEvents(List<Msg>, JsonNode, RuntimeContext)
  • HarnessAgent#streamEvents(List<Msg>, Class<?>, RuntimeContext)
  • HarnessAgent#streamEvents(List<Msg>, JsonNode, RuntimeContext)

Each overload simply routes m -> doCall(m, schema/class) through buildAgentStream, exactly mirroring call(msgs, schema/class, ctx) → callInternal(msgs, ctx, m -> doCall(m, schema/class)). This means:

  • native path: the model's response_format (strict json_schema) is preferred when supportsNativeStructuredOutput() is true; the JSON text surfaces as TextBlockDeltaEvents.
  • fallback path: when native is unsupported, the synthetic generate_response tool is injected and its ToolCallStartEvent / ToolCallDeltaEvent / tool-result events surface in the stream.
  • the final AgentResultEvent carries a Msg with hasStructuredData() == true plus aggregated token usage, semantically identical to the blocking call(...) result.

Tests

  • ReActAgentStreamEventsStructuredOutputTest (core): class/JsonNode overloads, fallback tool events + final structured result + usage, native TextBlockDeltaEvent JSON deltas, and semantic equivalence with call(...).
  • HarnessAgentStructuredOutputStreamEventsTest (harness): both overloads delegate structured output through the harness sandbox-lifecycle wrapper.

Notes

@codecov

codecov Bot commented Aug 31, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@dailingtao dailingtao left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@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.

LGTM. feat(agent): support structured output in streamEvents — change looks correct and clean.


Automated review by github-manager-bot

@dargoner

Copy link
Copy Markdown
Contributor

跟进一下这个 PR 的状态,顺带把 API 形状的问题摆到台面上。

现状核对:1 commit / 4 files,两个人工 approve(dailingtao、oss-maintainer),CI 5/5 通过,自 8-31 提交后没有新动作;分支落后 main 53 个提交。

同时 issue #1717(2.0 版本 streamEvents 增加结构化输出参数)是同一个 API 面诉求,目前两处并行挂着。建议维护者在这条 PR 上定个调子:

  1. 形状以哪一处为准:ReActAgent.streamEvents(List, Class<?>, RuntimeContext) 与 (List, JsonNode, RuntimeContext) 是否就是期望的签名;
  2. 是否希望补齐 Msg / String 形式的便捷重载(下游实际使用中这两类重载的调用频率更高,只有 List 形式的话上层还要自己包一层);
  3. core 与 harness 是否统一(HarnessAgent 侧同样需要,否则 harness 用户拿不到这个能力)。

之所以追问形状:我们下游已经按同样语义实现了 core + harness 的这套重载(含 Msg / String 便捷形式),如果官方签名定下来,我们可以直接对齐,避免出现「官方一套、下游一套」的长期分裂;#1717 里的提问者也能得到一个明确答复。

如果需要先 rebase 到最新 main 才能进入合并队列,也请说一下。

@Letter2025
Letter2025 force-pushed the feat/streamEvents-structured-output branch from f2aca34 to ce329fe Compare September 15, 2026 12:32
@Letter2025

Copy link
Copy Markdown
Contributor Author

Thanks @dargoner for the thorough follow-up — all three questions are addressed in the latest push (ce329fe6, rebased onto main @ 283f216d):

  1. API shape — streamEvents(List<Msg>, Class<?>, RuntimeContext) and streamEvents(List<Msg>, JsonNode, RuntimeContext) are the canonical shapes, mirroring the existing call(msgs, class/schema, ctx) semantics (native response_format first, synthetic generate_response fallback, final AgentResultEvent carrying validated structured data + usage). On top of that, the Msg / String convenience overloads you mentioned are now added — on both ReActAgent and HarnessAgent — so downstream callers no longer need to wrap into a List themselves (streamEvents(msg|text, class/schema, ctx)).

  2. core + harness alignment — both layers now expose the full overload set through the same buildAgentStream / wrappedStreamEvents cores as their non-structured siblings, with identical sandbox-lifecycle semantics.

  3. Rebase — rebased onto latest main (283f216d), no conflicts, spotless clean; targeted core (5 tests) and harness (3 tests) suites pass locally, CI is running on the new commit.

@oss-maintainer PTAL when you get a chance — thanks for the earlier approval.

(中文小结:形状以 List + Class/JsonNode + RuntimeContext 为准、与 call() 对齐;已补上 Msg/String 四组便捷重载,core 与 harness 两层都齐;已 rebase 到最新 main 无冲突,扩展测试本地全绿。)

@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-reviewed after the rebase + the new convenience overloads (f2aca34b → ce329fe6). The change is a faithful mirror of the call() structured family: streamEvents(msgs, Class|JsonNode, ctx) routes through the same buildAgentStream(msgs, context, m -> doCall(m, ...)) core that callInternal() uses, so "semantically equivalent to call()" holds by construction, and the harness side keeps ensureSessionDefaults + wrappedStreamEvents identical to the plain overload. 600 lines of tests covering both the native response_format path and the synthetic generate_response fallback, including a streamEvents vs call equivalence check. CLA signed, CI green. Approving — nothing below is blocking.

Findings

  • [Warning] HarnessAgent.java:1000 — the "same sandbox-lifecycle acquire/release semantics" claim is not pinned by any test; all three new harness cases use LocalFilesystem, so a regression that bypassed wrappedStreamEvents would still be green.
  • [Info] ReActAgent.java:1156 — the plain family has context-less entries (streamEvents(List), (Msg), (String)), every structured variant requires a RuntimeContext; small asymmetry users will trip over.
  • [Info] ReActAgent.java:1173 — Class<?> vs JsonNode in the same position makes streamEvents(msgs, null, ctx) an ambiguous-call compile error; the runtime guard exists in doStructuredCall, a Javadoc note would help.
  • [Info] ReActAgentStreamEventsStructuredOutputTest.java:300 — the call() equivalence assertion currently covers the fallback path; extending it to the native path closes the loop, since wrapNativeStructuredResult post-processes the Msg only there.

Suggestions

One sandbox-backed harness test asserting acquire+release exactly once per subscription for a structured overload is the highest-value addition; HarnessAgentSubagentStreamEventsTest already shows the shape.


Automated review by github-manager-bot

* @return event stream covering the full agent invocation lifecycle
*/
public Flux<AgentEvent> streamEvents(
List<Msg> msgs, Class<?> structuredModel, RuntimeContext ctx) {

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.

[Warning] The Javadoc here promises "the same sandbox-lifecycle acquire/release semantics" as the plain overload, and the delegation (ensureSessionDefaults + wrappedStreamEvents) does read identical to streamEvents(List, RuntimeContext) — but nothing pins that promise. The three new harness tests all build the agent with LocalFilesystem, so the acquire/release path is never entered. A regression that routes the structured overloads around wrappedStreamEvents (i.e. leaks a sandbox lease per structured streaming call under a real sandbox backend) would still leave this file green. Worth one test against the sandbox-backed harness that asserts acquire+release exactly once per subscription — HarnessAgentSubagentStreamEventsTest shows the pattern.

* @param context runtime context to propagate into the call
* @return event stream covering the full agent invocation lifecycle
*/
public Flux<AgentEvent> streamEvents(

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.

[Info] The plain family offers context-less entries (streamEvents(List<Msg>) at :1114, streamEvents(Msg) at :1124, streamEvents(String) at :1223), but every structured variant requires an explicit RuntimeContext. agent.streamEvents(msgs, WeatherResponse.class) therefore does not compile while agent.streamEvents(msgs) does — a small asymmetry users will trip over. Either add the two ctx-less overloads (delegating with null, exactly like :1114 does) or call the requirement out in the class-level docs, so "mirror the call() family" is true in shape and not only in semantics.

* @param context runtime context to propagate into the call
* @return event stream covering the full agent invocation lifecycle
*/
public Flux<AgentEvent> streamEvents(

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.

[Info] streamEvents(List, Class<?>, RuntimeContext) and streamEvents(List, JsonNode, RuntimeContext) make the second argument genuinely ambiguous for a null literal: streamEvents(msgs, null, ctx) is a compile error (reference ambiguous) rather than a clean failure. doStructuredCall already returns Mono.error(IllegalArgumentException) for "both null", so the runtime guard exists; a short Javadoc note (pass an explicit (Class<?>) null cast, or use the plain overload) plus one test asserting the error when a casted-null reaches doStructuredCall would make the intent explicit. Not blocking — call() at :851/:855 has the same shape, so this is consistent-by-inheritance.

.collectList()
.block(Duration.ofSeconds(10));
assertNotNull(msgSchemaEvents);
assertEquals(

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.

[Info] Nice to see streamEventsStructuredResultMatchesCallResult — asserting the streamed AgentResultEvent and the call() result agree is the check that actually protects the "semantically equivalent to call()" claim in the Javadoc. Extending that same equivalence assertion to the native path (currently only the fallback path is cross-checked against call()) would close the loop, since the native branch is the one where wrapNativeStructuredResult post-processes the Msg differently.

@Letter2025

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed notes @oss-maintainer — all four addressed in 1c9caff8:

  1. [Warning] sandbox acquire/release not pinned — added sandboxBackedStreamEvents_acquiresAndReleasesExactlyOncePerSubscription in HarnessAgentStructuredOutputStreamEventsTest: a sandbox-backed HarnessAgent (InMemorySandboxFilesystemSpec) runs two structured streams against the same session and asserts InMemorySandboxClient.createCount == 1 then resumeCount == 1 — i.e. acquire exactly once per subscription, and release persists state exactly once (a regression that routes the structured overloads around wrappedStreamEvents would never enter the sandbox path and fails the create/resume counts).
  2. [Info] context-less asymmetry — added streamEvents(List, Class<?>) and streamEvents(List, JsonNode) on ReActAgent, delegating with a null context exactly like the plain streamEvents(List) entry; covered by contextlessClassAndSchemaOverloadsYieldStructuredResults.
  3. [Info] null-literal ambiguity — Javadoc note added to both 3-arg structured overloads (bare null is ambiguous between the Class/JsonNode siblings; cast explicitly or use the plain overload), plus castedNullStructuredArgumentFailsFastClearly asserting a casted-null surfaces the existing IllegalArgumentException from doStructuredCall when nothing is provided.
  4. [Info] native-path equivalence — added streamEventsNativePathMatchesCallResult, cross-checking the AgentResultEvent against call(...) on the native response_format path (where wrapNativeStructuredResult post-processes the Msg), mirroring the existing fallback-path equivalence test.

Local: core ReActAgentStreamEventsStructuredOutputTest 8/8 and harness HarnessAgentStructuredOutputStreamEventsTest 4/4 green, spotless clean. @oss-maintainer PTAL when convenient — thanks again for the review.

@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

Delta re-review of ce329fe6 → 1c9caff8 — the commit carrying my four non-blocking items from the previous approval. All four are addressed, and the fixes are the right kind: two of them are tests that pin behaviour previously asserted only in prose, so the claim cannot rot silently.

  • Sandbox acquire/release — sandboxBackedStreamEvents_acquiresAndReleasesExactlyOncePerSubscription drives a real InMemorySandboxFilesystemSpec and asserts exactly one create on the first subscription and exactly one resume on the second, i.e. wrappedStreamEvents' acquire/release is now pinned per subscription instead of being inherited by analogy from the plain overload. That was my main item; it is closed.
  • Casted-null structuredOutputClass / outputSchema — javadoc on both 3-arg overloads now names the ambiguity and points at the explicit cast or the plain overload, and castedNullStructuredArgumentFailsFastClearly pins the exception message (targetClass or schemaDesc) rather than merely that it throws.
  • Context-less form — streamEvents(msgs, Class) / streamEvents(msgs, JsonNode) delegate to the 3-arg version with (RuntimeContext) null, so they cannot diverge from the default-context path, and contextlessClassAndSchemaOverloadsYieldStructuredResults covers both.
  • Native-vs-call equivalence — streamEventsNativePathMatchesCallResult compares the streamEvents(...) and call(...) structured payloads on the same fixture model, which is the check the "semantically equivalent to call()" claim actually needs.

Findings

  • [Info] ReActAgent.java:1126 / :1138 — the context-less structured pair exists only on ReActAgent. HarnessAgent offers streamEvents(msgs, Class, ctx) (:999) and (msgs, JsonNode, ctx) (:1017) but no (msgs, Class) / (msgs, JsonNode), so callers who start from HarnessAgent — the documented entry point — lose exactly the convenience this commit adds, and the asymmetry reads as a missing feature rather than a choice. Mirroring the two delegating one-liners on the harness side, or noting the difference in the javadoc, keeps the two surfaces consistent. Not blocking.

Verification

The delta is confined to ReActAgent.java (+32 lines: javadoc plus two delegating overloads) and the two test classes; no change on the already-approved path, so the earlier reasoning still holds. CLA signed (license/cla=success on 1c9caff8). CI on the new head was still PENDING when this review was written (build ubuntu/windows, validate, license) — this approves the code, not the pipeline; if a check goes red the fix is the author's and I will re-check on the next sweep.


Automated review by github-manager-bot

@Letter2025

Copy link
Copy Markdown
Contributor Author

Thanks — addressed the remaining [Info] with edaed31e.

On the harness side I went with your second option (javadoc note) rather than mirroring the context-less pair: HarnessAgent's existing context-less plain streamEvents entries (streamEvents(Msg), streamEvents(List<Msg>), streamEvents(String)) are all @Deprecated(since = "2.2.0") in favor of an explicit RuntimeContext, so adding new non-deprecated context-less structured overloads would fight that API direction. Both 3-arg structured overloads now carry the note recording the deliberate asymmetry vs ReActAgent.

Everything else on this PR stands as previously reviewed: CI on the current head is running (Module Sync + License already green). @oss-maintainer thanks again for the thorough passes.

@Letter2025

Copy link
Copy Markdown
Contributor Author

Heads-up on the red Windows check on edaed31e — it's a pre-existing flake, unrelated to the diff:

  • The only failure is LocalFilesystemPersonalAssistantExampleTest.localFilesystem_filesPersistAcrossCalls (MEMORY.md content should be unchanged after call 2) — 1043 of 1044 harness tests passed, and every test added by this PR passed.
  • The edaed31e diff is javadoc-only (8 insertions, no executable code).
  • The same class (including that exact test) passes 3/3 locally on Windows.
  • The failure mode is the familiar harness background memory-flush race: the flush/maintenance scheduler writes MEMORY.md asynchronously after the call completes, so an immediate "unchanged" assertion can catch a late write. We've reported the same family of flakes before on other PRs (e.g. Failed to close extension context at @TempDir teardown on unrelated main runs).

Since the fork account cannot rerun the workflow on this repo, I pushed d0363392 — an empty commit with no file changes — purely to trigger a fresh CI run. @oss-maintainer if the rerun comes back green (as expected), this should be ready to merge.

@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

Delta since my previous approval is documentation-only (+8 lines of javadoc on HarnessAgent#streamEvents(..., structuredModel, ctx) / (…, schema, ctx) explaining why the context-less structured overloads are deliberately absent) plus a CI re-run commit with no code change. Nothing behavioral — the earlier approval stands on the new head. CLA signed, MERGEABLE/CLEAN.


Automated review by github-manager-bot

dargoner added a commit to dargoner/agentscope-java that referenced this pull request Sep 27, 2026
@jujn jujn added the P2 重要不紧急 label Nov 4, 2026
@liyujiang-gzu

Copy link
Copy Markdown

进展如何了?

Letter2025 and others added 6 commits November 20, 2026 14:27
Add fine-grained structured-output overloads to the v2 streaming API so callers can stream validated structured JSON without depending on the deprecated coarse-grained stream(...) methods.

- ReActAgent.streamEvents(List, Class, RuntimeContext)
- ReActAgent.streamEvents(List, JsonNode, RuntimeContext)
- HarnessAgent mirrors both overloads with sandbox-lifecycle semantics

Both reuse the existing buildAgentStream core with doCall(m, schema/class), so the native response_format path and the synthetic generate_response fallback behave identically to call(msgs, schema/class, ctx). The final AgentResultEvent carries the validated structured Msg (hasStructuredData() == true) plus aggregated token usage.

Closes agentscope-ai#1717
…amEvents

Mirror the call(...) convenience family so downstream callers do not need to wrap Msg/String inputs into a List themselves (the shape most callers actually use, per community feedback):

- ReActAgent: streamEvents(Msg|String, Class|JsonNode, RuntimeContext)
- HarnessAgent: the same four overloads, delegating through wrappedStreamEvents with sandbox-lifecycle semantics

Rebased onto latest main (283f216).
All four review comments from the latest round:

- ReActAgent: context-less overloads streamEvents(List, Class) and
  streamEvents(List, JsonNode), mirroring the plain family
- ReActAgent: Javadoc note on the null-literal overload ambiguity of the
  3-arg structured overloads + fast-fail test for a casted-null
- test: extend the streamEvents/call() semantic-equivalence assertion to
  the native response_format path
- test: sandbox-backed HarnessAgent subscription asserts acquire/release
  exactly once per structured stream (create=1, then resume=1)
…eamEvents overloads

HarnessAgent intentionally offers no context-less structured overloads: its context-less plain streamEvents entries are deprecated since 2.2.0 in favor of an explicit RuntimeContext, and the asymmetry vs ReActAgent is now recorded on both structured overloads.
Windows job failed in LocalFilesystemPersonalAssistantExampleTest.localFilesystem_filesPersistAcrossCalls (MEMORY.md background flush races the assertion) with 1043 of 1044 tests passing; the same test class passes 3/3 locally. This commit changes no files and only triggers a fresh CI run.
@jujn
jujn force-pushed the feat/streamEvents-structured-output branch from d036339 to 322c4cc Compare November 20, 2026 07:02
@jujn
jujn merged commit 131e3fe into agentscope-ai:main Nov 20, 2026
3 of 5 checks passed
xzxiaoshan added a commit to xzxiaoshan/agentscope-java that referenced this pull request Nov 23, 2026
Merge main (decbe55, 41 commits) into the final-answer-gate branch and
resolve:

- AgentScopeAdapterTest / RocketMqExecutionTest (content conflicts):
  both sides widened the same await budgets for loaded CI runners —
  this branch (bfb7e33) with literals, main (agentscope-ai#4274) with the named
  TURN_DEADLINE / AWAIT_DEADLINE_SECONDS constants and waitUntil,
  covering every site this branch touched with equal or wider budgets.
  Take main's version of both files; they are now identical to main,
  which supersedes this branch's deflake.
- ReActAgent (auto-merged): main's only change (agentscope-ai#2919) adds structured-
  output call/streamEvents overloads that delegate to doCall, so they
  run through the same gated exits. The merged file is main plus this
  branch's feature delta, verified line by line.

Verified: mvn -T1C clean test-compile over the whole reactor (114
modules, spotless:check clean); core and harness full suites (3573 and
1918 tests, 0 failures), including ReActAgentFinalAnswerGateTest (58)
and main's new ReActAgentStreamEventsStructuredOutputTest (7); core
package with javadoc doclint; RocketMqExecutionTest 5/5; docs npm test
20/20 and build validation.

Not introduced here — reproduced identically on main and on the
pre-merge branch head on this Windows machine:
AgentScopeAdapterTest
nativeHarnessWorkspaceForkCopiesPrivateFilesWithoutSharingSubsequentWrites
and realHarnessMemoryFinalizationReplaysRecordedSummaryAfterRestart fail
(39/41 pass); `mint broken-links` reports the same 2750 internal links
on main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2.0版本streamEvents增加结构化输出参数

6 participants