Repository navigation
feat(agent): support structured output in streamEvents - #2919
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
LGTM. feat(agent): support structured output in streamEvents — change looks correct and clean.
Automated review by github-manager-bot
|
跟进一下这个 PR 的状态,顺带把 API 形状的问题摆到台面上。 现状核对:1 commit / 4 files,两个人工 approve(dailingtao、oss-maintainer),CI 5/5 通过,自 8-31 提交后没有新动作;分支落后 main 53 个提交。 同时 issue #1717(2.0 版本 streamEvents 增加结构化输出参数)是同一个 API 面诉求,目前两处并行挂着。建议维护者在这条 PR 上定个调子:
之所以追问形状:我们下游已经按同样语义实现了 core + harness 的这套重载(含 Msg / String 便捷形式),如果官方签名定下来,我们可以直接对齐,避免出现「官方一套、下游一套」的长期分裂;#1717 里的提问者也能得到一个明确答复。 如果需要先 rebase 到最新 main 才能进入合并队列,也请说一下。 |
f2aca34 to
ce329fe
Compare
|
Thanks @dargoner for the thorough follow-up — all three questions are addressed in the latest push (
@oss-maintainer PTAL when you get a chance — thanks for the earlier approval. (中文小结:形状以 |
oss-maintainer
left a comment
There was a problem hiding this comment.
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 useLocalFilesystem, so a regression that bypassedwrappedStreamEventswould still be green. - [Info]
ReActAgent.java:1156— the plain family has context-less entries (streamEvents(List),(Msg),(String)), every structured variant requires aRuntimeContext; small asymmetry users will trip over. - [Info]
ReActAgent.java:1173—Class<?>vsJsonNodein the same position makesstreamEvents(msgs, null, ctx)an ambiguous-call compile error; the runtime guard exists indoStructuredCall, a Javadoc note would help. - [Info]
ReActAgentStreamEventsStructuredOutputTest.java:300— thecall()equivalence assertion currently covers the fallback path; extending it to the native path closes the loop, sincewrapNativeStructuredResultpost-processes theMsgonly 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) { |
There was a problem hiding this comment.
[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( |
There was a problem hiding this comment.
[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( |
There was a problem hiding this comment.
[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( |
There was a problem hiding this comment.
[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.
|
Thanks for the detailed notes @oss-maintainer — all four addressed in
Local: core |
oss-maintainer
left a comment
There was a problem hiding this comment.
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_acquiresAndReleasesExactlyOncePerSubscriptiondrives a realInMemorySandboxFilesystemSpecand 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, andcastedNullStructuredArgumentFailsFastClearlypins 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, andcontextlessClassAndSchemaOverloadsYieldStructuredResultscovers both. - Native-vs-
callequivalence —streamEventsNativePathMatchesCallResultcompares thestreamEvents(...)andcall(...)structured payloads on the same fixture model, which is the check the "semantically equivalent tocall()" claim actually needs.
Findings
- [Info]
ReActAgent.java:1126/:1138— the context-less structured pair exists only onReActAgent.HarnessAgentoffersstreamEvents(msgs, Class, ctx)(:999) and(msgs, JsonNode, ctx)(:1017) but no(msgs, Class)/(msgs, JsonNode), so callers who start fromHarnessAgent— 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
|
Thanks — addressed the remaining [Info] with On the harness side I went with your second option (javadoc note) rather than mirroring the context-less pair: 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. |
|
Heads-up on the red Windows check on
Since the fork account cannot rerun the workflow on this repo, I pushed |
oss-maintainer
left a comment
There was a problem hiding this comment.
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
|
进展如何了? |
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.
d036339 to
322c4cc
Compare
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.
Problem
The fine-grained streaming API (
ReActAgent#streamEvents(...)) — the recommended replacement for the deprecated coarse-grainedstream(...)— has no structured-output overloads. Onlycall(msgs, schema/class, ctx)(non-streaming) and the deprecatedstream(msgs, options, schema/class, ctx)supportoutputSchema.buildAgentStream(...)is private, so downstream code cannot inject a schema variant ofstreamEventswithout forking the framework or relying on the deprecated API (which returns the legacyio.agentscope.core.agent.Eventinstead of the fine-grainedio.agentscope.core.event.AgentEvent).Closes #1717.
Change
Add the missing fine-grained overloads, reusing the existing
buildAgentStreamcore 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)throughbuildAgentStream, exactly mirroringcall(msgs, schema/class, ctx)→callInternal(msgs, ctx, m -> doCall(m, schema/class)). This means:response_format(strictjson_schema) is preferred whensupportsNativeStructuredOutput()is true; the JSON text surfaces asTextBlockDeltaEvents.generate_responsetool is injected and itsToolCallStartEvent/ToolCallDeltaEvent/ tool-result events surface in the stream.AgentResultEventcarries aMsgwithhasStructuredData() == trueplus aggregated tokenusage, semantically identical to the blockingcall(...)result.Tests
ReActAgentStreamEventsStructuredOutputTest(core): class/JsonNode overloads, fallback tool events + final structured result + usage, nativeTextBlockDeltaEventJSON deltas, and semantic equivalence withcall(...).HarnessAgentStructuredOutputStreamEventsTest(harness): both overloads delegate structured output through the harness sandbox-lifecycle wrapper.Notes
stream(...)API; those overloads remain as-is.streamEventsis intentionally left for a follow-up (see HarnessAgent和ReActAgent 中streamEvent 为什么不放在Agent接口层 #1894); this PR only adds the concreteReActAgent/HarnessAgentoverloads requested in 2.0版本streamEvents增加结构化输出参数 #1717.