Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(agent): populate structured output and resolve deferred @structured (#20679)

天海蒼灆c44c69704be8
diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.go
index e44c4dd71a..9a2a0e23de 100644
--- a/internal/agent/component/agent.go
+++ b/internal/agent/component/agent.go
@@ -75,7 +75,6 @@ type AgentParam struct {
Description string
SystemPrompt string
UserPrompt string
- OutputStructure map[string]any
Thinking string
MaxTokens *int
TopP *float64
@@ -112,6 +111,12 @@ type AgentParam struct {
MaxTokensDisabled bool
TopPDisabled bool
TemperatureDisabled bool
+
+ // OutputStructure is the expected top-level JSON key set for the
+ // Agent's structured output. Canvas DSL stores the JSON Schema under
+ // outputs.structured; when set, Invoke populates outputs["structured"]
+ // so downstream Message templates like {Agent:X@structured} resolve.
+ OutputStructure map[string]any
}
// SubAgentTool is a child Agent exposed to a parent Agent as an Eino tool.
@@ -223,7 +228,7 @@ func runEinoReActAgent(ctx context.Context, p AgentParam) (*schema.Message, erro
// started signal (closed by the graph onStart callback), so starting
// the collector first lets non-citation deltas stream out in real time
// while the checker runs, instead of buffering the entire round.
- emitDone := emitAgentModelStreams(ctx, future, p.Cite)
+ emitDone := emitAgentModelStreams(ctx, future, p.Cite, len(p.OutputStructure) > 0)
stream, err := agent.Stream(ctx, input, opt)
if err != nil {
// Drain the collector so its goroutine exits before we return.
@@ -409,7 +414,7 @@ func buildAgentInputMessages(ctx context.Context, p AgentParam) []*schema.Messag
return input
}
-func emitAgentModelStreams(ctx context.Context, future react.MessageFuture, cite bool) <-chan error {
+func emitAgentModelStreams(ctx context.Context, future react.MessageFuture, cite bool, holdContent bool) <-chan error {
done := make(chan error, 1)
go func() {
var firstErr error
@@ -458,7 +463,17 @@ func emitAgentModelStreams(ctx context.Context, future react.MessageFuture, cite
if runtime.AgentMessageEventsEmitted(ctx) && !runtime.HasDeferredAgentMessageSink(ctx) {
continue
}
- runtime.EmitAgentMessage(ctx, msg.Content, msg.ReasoningContent)
+ content := msg.Content
+ if holdContent {
+ // Structured outputs are normalized (fence-stripped) after the
+ // model finishes. Do not stream the raw body; invokeNow emits
+ // the cleaned content once so SSE matches outputs["content"].
+ content = ""
+ }
+ if content == "" && msg.ReasoningContent == "" {
+ continue
+ }
+ runtime.EmitAgentMessage(ctx, content, msg.ReasoningContent)
}
msgStream.Close()
}
@@ -590,6 +605,12 @@ func applyCitationGrounding(ctx context.Context, db *gorm.DB, p AgentParam, cont
if isThink || delta == "" {
return nil
}
+ // Structured output is normalized once after grounding. Streaming
+ // these deltas would duplicate that final emission, and the raw
+ // chunks would not match the cleaned content.
+ if len(p.OutputStructure) > 0 {
+ return nil
+ }
return emitContent(streamFilter.Push(delta))
})
if err == nil {
@@ -1051,8 +1072,12 @@ func (c *AgentComponent) invokeNow(ctx context.Context, db *gorm.DB, inputs map[
}
}
if len(p.OutputStructure) > 0 {
- keys := make([]string, 0, len(p.OutputStructure))
- for key := range p.OutputStructure {
+ keySource := p.OutputStructure
+ if props, ok := p.OutputStructure["properties"].(map[string]any); ok && len(props) > 0 {
+ keySource = props
+ }
+ keys := make([]string, 0, len(keySource))
+ for key := range keySource {
keys = append(keys, key)
}
sort.Strings(keys)
@@ -1167,16 +1192,31 @@ func (c *AgentComponent) invokeNow(ctx context.Context, db *gorm.DB, inputs map[
if invocations := p.toolInvocations.snapshot(); len(invocations) > 0 {
out["tool_invocations"] = invocations
}
- if len(p.OutputStructure) > 0 {
- if parsed, ok := matchOutputStructure(cleanFormattedAnswer(content), p.OutputStructure); ok {
- out["structured"] = parsed
- }
- }
if groundingStatus != "" {
out["grounding_status"] = groundingStatus
}
+ structuredHeld := len(p.OutputStructure) > 0
+ if structuredHeld {
+ cleaned := strings.TrimSpace(cleanFormattedAnswer(content))
+ parsed, ok := matchAgentOutputStructure(cleaned, p.OutputStructure)
+ if !ok {
+ parsed, ok = matchAgentOutputStructure(content, p.OutputStructure)
+ }
+ if ok {
+ out["structured"] = parsed
+ out["content"] = cleaned + artifactMD
+ content = cleaned
+ } else {
+ common.Warn("component: Agent: outputs.structured set but no parseable JSON matching schema",
+ zap.Strings("expected_keys", sortedMapKeys(structuredExpectedKeySet(p.OutputStructure))))
+ }
+ }
streamed := runtime.AgentMessageEventsEmitted(ctx) || runtime.DeferredAgentMessageEventsEmitted(ctx)
switch {
+ case structuredHeld:
+ // Content deltas were held above; emit the normalized body once so the
+ // live stream matches outputs["content"] (no fenced/raw mismatch).
+ runtime.EmitAgentMessage(ctx, content+artifactMD, "")
case !streamed:
runtime.EmitAgentMessage(ctx, content+artifactMD, thinking)
case artifactMD != "":
@@ -1634,11 +1674,6 @@ func mergeAgentParam(base AgentParam, inputs map[string]any) AgentParam {
if v, ok := stringFrom(inputs, "description"); ok {
p.Description = v
}
- if outputs, ok := inputs["outputs"].(map[string]any); ok {
- if structured, ok := outputs["structured"].(map[string]any); ok {
- p.OutputStructure, _ = structured["properties"].(map[string]any)
- }
- }
if v, ok := stringFrom(inputs, "system_prompt"); ok {
p.SystemPrompt = v
} else if v, ok := stringFrom(inputs, "sys_prompt"); ok {
@@ -1709,9 +1744,214 @@ func mergeAgentParam(base AgentParam, inputs map[string]any) AgentParam {
if v, ok := boolFrom(inputs, "cite"); ok {
p.Cite = v
}
+ if keys := agentOutputStructureFrom(inputs); len(keys) > 0 {
+ p.OutputStructure = keys
+ }
return p
}
+// agentOutputStructureFrom reads the Agent's structured-output schema from
+// either the LLM-style output_structure map or the canvas outputs.structured
+// JSON Schema. The raw map is preserved so matchAgentOutputStructure can honor
+// required vs properties and declared property types.
+func agentOutputStructureFrom(inputs map[string]any) map[string]any {
+ if v, ok := mapFrom(inputs, "output_structure"); ok {
+ return v
+ }
+ outputs, ok := mapFrom(inputs, "outputs")
+ if !ok {
+ return nil
+ }
+ structured, ok := mapFrom(outputs, "structured")
+ if !ok || len(structured) == 0 {
+ return nil
+ }
+ return structured
+}
+
+// matchAgentOutputStructure parses content against a flat key hint or a JSON
+// Schema object. Flat hints require every listed key. JSON Schema requires only
+// `required` keys (properties alone do not imply required), checks declared
+// top-level property types, rejects a null document when the root type excludes
+// null, and rejects keys outside properties when additionalProperties is false.
+func matchAgentOutputStructure(content string, structure map[string]any) (map[string]any, bool) {
+ if strings.TrimSpace(content) == "null" {
+ types, hasType := schemaTypeNames(structure["type"])
+ if !hasType {
+ // An omitted type does not exclude null. required applies only to objects.
+ if isJSONSchemaObject(structure) {
+ return nil, true
+ }
+ } else {
+ for _, typ := range types {
+ if typ == "null" {
+ return nil, true
+ }
+ }
+ return nil, false
+ }
+ }
+ expected := structuredExpectedKeySet(structure)
+ parsed, ok := matchOutputStructure(content, expected)
+ if !ok {
+ return nil, false
+ }
+ if props, ok := structure["properties"].(map[string]any); ok && len(props) > 0 {
+ if !matchStructuredPropertyTypes(parsed, props) {
+ return nil, false
+ }
+ }
+ if structure["additionalProperties"] == false {
+ props, _ := structure["properties"].(map[string]any)
+ for k := range parsed {
+ if _, declared := props[k]; !declared {
+ return nil, false
+ }
+ }
+ }
+ return parsed, true
+}
+
+// structuredExpectedKeySet turns a JSON Schema (properties/required) or a
+// flat key map into the key set matchOutputStructure checks against.
+func structuredExpectedKeySet(schema map[string]any) map[string]any {
+ if isJSONSchemaObject(schema) {
+ keys := make(map[string]any)
+ if req, ok := schema["required"].([]any); ok {
+ for _, item := range req {
+ if s, ok := item.(string); ok && s != "" {
+ keys[s] = true
+ }
+ }
+ }
+ // No required → empty key set: any JSON object passes the presence check.
+ return keys
+ }
+ return schema
+}
+
+func isJSONSchemaObject(schema map[string]any) bool {
+ if _, ok := schema["type"]; ok {
+ return true
+ }
+ if _, ok := schema["properties"]; ok {
+ return true
+ }
+ if _, ok := schema["required"]; ok {
+ return true
+ }
+ return false
+}
+
+func matchStructuredPropertyTypes(parsed map[string]any, props map[string]any) bool {
+ for k, propSchema := range props {
+ v, present := parsed[k]
+ if !present {
+ continue
+ }
+ ps, ok := propSchema.(map[string]any)
+ if !ok {
+ continue
+ }
+ types, ok := schemaTypeNames(ps["type"])
+ if !ok {
+ continue
+ }
+ matched := false
+ for _, typ := range types {
+ if jsonValueMatchesSchemaType(v, typ) {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ return false
+ }
+ }
+ return true
+}
+
+// schemaTypeNames reads a JSON Schema type keyword. It is a single string or
+// an array of strings. An omitted or empty type reports ok=false.
+func schemaTypeNames(raw any) ([]string, bool) {
+ switch t := raw.(type) {
+ case string:
+ if t == "" {
+ return nil, false
+ }
+ return []string{t}, true
+ case []string:
+ if len(t) == 0 {
+ return nil, false
+ }
+ return t, true
+ case []any:
+ names := make([]string, 0, len(t))
+ for _, item := range t {
+ s, ok := item.(string)
+ if !ok || s == "" {
+ continue
+ }
+ names = append(names, s)
+ }
+ if len(names) == 0 {
+ return nil, false
+ }
+ return names, true
+ default:
+ return nil, false
+ }
+}
+
+func jsonValueMatchesSchemaType(v any, typ string) bool {
+ switch typ {
+ case "string":
+ _, ok := v.(string)
+ return ok
+ case "number":
+ switch v.(type) {
+ case float64, json.Number, int, int32, int64:
+ return true
+ default:
+ return false
+ }
+ case "integer":
+ switch x := v.(type) {
+ case float64:
+ return x == float64(int64(x))
+ case json.Number:
+ _, err := x.Int64()
+ return err == nil
+ case int, int32, int64:
+ return true
+ default:
+ return false
+ }
+ case "boolean":
+ _, ok := v.(bool)
+ return ok
+ case "object":
+ _, ok := v.(map[string]any)
+ return ok
+ case "array":
+ _, ok := v.([]any)
+ return ok
+ case "null":
+ return v == nil
+ default:
+ return true
+ }
+}
+
+func sortedMapKeys(m map[string]any) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
// agentToolsFrom extracts the Agent tools list. The Go-native shape is
// []string; the canvas DSL shape stores tool component objects with
// component_name and params. Child Agent objects are returned separately
diff --git a/internal/agent/component/agent_test.go b/internal/agent/component/agent_test.go
index bf3fd360cf..154c81613f 100644
--- a/internal/agent/component/agent_test.go
+++ b/internal/agent/component/agent_test.go
@@ -80,6 +80,222 @@ func TestAgent_NoToolsReAct(t *testing.T) {
}
}
+func TestAgent_PopulatesStructuredFromOutputsSchema(t *testing.T) {
+ withAgentRunner(t, func(_ context.Context, _ AgentParam) (*schema.Message, error) {
+ return &schema.Message{
+ Role: schema.Assistant,
+ Content: "```json\n{\"records\":[{\"ruleId\":\"r1\",\"verdict\":\"PASS\"}],\"opinion\":{\"conclusion\":\"PASS\"}}\n```",
+ }, nil
+ })
+
+ c := NewAgentComponent(agentParamFromMap(map[string]any{
+ "model_id": "stub",
+ "outputs": map[string]any{
+ "structured": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "records": map[string]any{"type": "array"},
+ "opinion": map[string]any{"type": "object"},
+ },
+ "required": []any{"records"},
+ },
+ },
+ }))
+ out, err := c.Invoke(t.Context(), nil, map[string]any{
+ "user_prompt": "summarize",
+ })
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ structured, ok := out["structured"].(map[string]any)
+ if !ok {
+ t.Fatalf("structured missing or wrong type: %T (%v)", out["structured"], out["structured"])
+ }
+ if _, ok := structured["records"]; !ok {
+ t.Fatalf("structured.records missing: %#v", structured)
+ }
+ if got, want := out["content"], `{"records":[{"ruleId":"r1","verdict":"PASS"}],"opinion":{"conclusion":"PASS"}}`; got != want {
+ t.Errorf("content=%q, want cleaned JSON %q", got, want)
+ }
+}
+
+func TestAgentOutputStructureFromPreservesSchema(t *testing.T) {
+ schema := agentOutputStructureFrom(map[string]any{
+ "outputs": map[string]any{
+ "structured": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "records": map[string]any{"type": "array"},
+ "opinion": map[string]any{"type": "object"},
+ },
+ "required": []any{"records"},
+ },
+ },
+ })
+ if got, _ := schema["type"].(string); got != "object" {
+ t.Fatalf("expected full schema preserved, got %#v", schema)
+ }
+ keys := structuredExpectedKeySet(schema)
+ if len(keys) != 1 {
+ t.Fatalf("expected only required keys, got %#v", keys)
+ }
+ if _, ok := keys["records"]; !ok {
+ t.Fatalf("records key missing: %#v", keys)
+ }
+}
+
+func TestStructuredExpectedKeySet_PropertiesWithoutRequired(t *testing.T) {
+ keys := structuredExpectedKeySet(map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ "note": map[string]any{"type": "string"},
+ },
+ })
+ if len(keys) != 0 {
+ t.Fatalf("properties without required must not imply required keys, got %#v", keys)
+ }
+ parsed, ok := matchAgentOutputStructure(`{"id":1}`, map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ "note": map[string]any{"type": "string"},
+ },
+ })
+ if !ok {
+ t.Fatal("optional note missing should still match")
+ }
+ if _, ok := parsed["id"]; !ok {
+ t.Fatalf("parsed=%#v", parsed)
+ }
+}
+
+func TestMatchAgentOutputStructure_RejectsWrongType(t *testing.T) {
+ schema := map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ },
+ "required": []any{"id"},
+ }
+ if _, ok := matchAgentOutputStructure(`{"id":"wrong"}`, schema); ok {
+ t.Fatal("string id must fail integer type check")
+ }
+ if _, ok := matchAgentOutputStructure(`{"id":1}`, schema); !ok {
+ t.Fatal("integer id should pass")
+ }
+}
+
+func TestMatchAgentOutputStructure_RejectsNullForObjectSchema(t *testing.T) {
+ schema := map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ },
+ }
+ if _, ok := matchAgentOutputStructure("null", schema); ok {
+ t.Fatal("null must fail an object schema")
+ }
+ if _, ok := matchAgentOutputStructure("null", map[string]any{
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ },
+ }); !ok {
+ t.Fatal("omitted type must still accept null")
+ }
+ if _, ok := matchAgentOutputStructure("null", map[string]any{
+ "type": []any{"object", "null"},
+ "properties": map[string]any{"id": map[string]any{"type": "integer"}},
+ "required": []any{"id"},
+ }); !ok {
+ t.Fatal("type union that includes null must accept null")
+ }
+}
+
+func TestMatchAgentOutputStructure_RejectsAdditionalProperties(t *testing.T) {
+ schema := map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ },
+ "additionalProperties": false,
+ }
+ if _, ok := matchAgentOutputStructure(`{"id":1,"unexpected":true}`, schema); ok {
+ t.Fatal("undeclared key must fail when additionalProperties is false")
+ }
+ if _, ok := matchAgentOutputStructure(`{"id":1}`, schema); !ok {
+ t.Fatal("declared key should pass")
+ }
+}
+
+func TestMatchAgentOutputStructure_AcceptsTypeUnion(t *testing.T) {
+ schema := map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "note": map[string]any{"type": []any{"string", "null"}},
+ },
+ "required": []any{"note"},
+ }
+ if _, ok := matchAgentOutputStructure(`{"note":1}`, schema); ok {
+ t.Fatal("number must fail a string|null property")
+ }
+ if _, ok := matchAgentOutputStructure(`{"note":"ok"}`, schema); !ok {
+ t.Fatal("string should pass a string|null property")
+ }
+ if _, ok := matchAgentOutputStructure(`{"note":null}`, schema); !ok {
+ t.Fatal("null should pass a string|null property")
+ }
+}
+
+func TestAgent_StructuredDeferredEmitsCleanedContent(t *testing.T) {
+ withAgentRunner(t, func(ctx context.Context, _ AgentParam) (*schema.Message, error) {
+ runtime.EmitAgentMessage(ctx, "", "thinking")
+ return &schema.Message{
+ Role: schema.Assistant,
+ Content: "```json\n{\"records\":[]}\n```",
+ }, nil
+ })
+
+ ctx := runtime.WithComponentExecutionOptions(t.Context(), runtime.ComponentExecutionOptions{
+ DeferAgentToMessage: true,
+ })
+ c := NewAgentComponent(agentParamFromMap(map[string]any{
+ "model_id": "stub",
+ "outputs": map[string]any{
+ "structured": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "records": map[string]any{"type": "array"},
+ },
+ "required": []any{"records"},
+ },
+ },
+ }))
+ out, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "hello"})
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ deferred, ok := out["content"].(*runtime.DeferredStream)
+ if !ok || deferred == nil {
+ t.Fatalf("content=%T, want *runtime.DeferredStream", out["content"])
+ }
+
+ var streamed strings.Builder
+ final, err := deferred.Open(ctx, func(contentDelta, _ string) {
+ streamed.WriteString(contentDelta)
+ })
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ want := `{"records":[]}`
+ if got := streamed.String(); got != want {
+ t.Fatalf("streamed=%q, want cleaned %q", got, want)
+ }
+ if got, _ := final["content"].(string); got != want {
+ t.Fatalf("final content=%q, want %q", got, want)
+ }
+}
+
func TestScanAllStreamForToolCallWaitsPastTextChunks(t *testing.T) {
stream := schema.StreamReaderFromArray([]*schema.Message{
{Role: schema.Assistant, Content: "I will calculate this."},
@@ -315,7 +531,7 @@ func TestReactCheckerStreamsThinkingBeforeAgentReturns(t *testing.T) {
})
opt, future := react.WithMessageFuture()
- emitDone := emitAgentModelStreams(ctx, future, false)
+ emitDone := emitAgentModelStreams(ctx, future, false, false)
streamCh := make(chan *schema.StreamReader[*schema.Message], 1)
errCh := make(chan error, 1)
diff --git a/internal/agent/component/grounding_test.go b/internal/agent/component/grounding_test.go
index 1fa6570dbe..2879d3a2df 100644
--- a/internal/agent/component/grounding_test.go
+++ b/internal/agent/component/grounding_test.go
@@ -132,6 +132,61 @@ func TestGrounding_Applied(t *testing.T) {
}
}
+func TestGrounding_StructuredEmitsCleanedContentOnce(t *testing.T) {
+ inv := &groundingStreamingInvoker{groundingTestInvoker: groundingTestInvoker{
+ responses: []string{"```json\n{\"id\":1}\n```"},
+ }}
+ prev := getDefaultChatInvoker()
+ SetDefaultChatInvoker(inv)
+ defer SetDefaultChatInvoker(prev)
+
+ withAgentRunner(t, func(_ context.Context, _ AgentParam) (*schema.Message, error) {
+ return &schema.Message{Role: schema.Assistant, Content: "```json\n{\"id\":1}\n```"}, nil
+ })
+
+ state := canvas.NewCanvasState("r1", "t1")
+ state.SetRetrievalChunks([]map[string]any{
+ {"id": "0", "content": "the source content"},
+ })
+ ctx := runtime.WithState(t.Context(), state)
+ var streamed string
+ var deltas int
+ ctx = runtime.WithAgentMessageEmitter(ctx, func(content, _ string) {
+ streamed += content
+ deltas++
+ })
+
+ c := NewAgentComponent(agentParamFromMap(map[string]any{
+ "model_id": "stub",
+ "cite": true,
+ "outputs": map[string]any{
+ "structured": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "id": map[string]any{"type": "integer"},
+ },
+ "required": []any{"id"},
+ },
+ },
+ }))
+ out, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "q"})
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ if _, ok := out["structured"].(map[string]any); !ok {
+ t.Fatalf("structured=%T (%v)", out["structured"], out["structured"])
+ }
+ if deltas != 1 {
+ t.Fatalf("deltas=%d, want 1 (grounding must not emit before the cleaned answer)", deltas)
+ }
+ if streamed != out["content"] {
+ t.Fatalf("streamed=%q, content=%q", streamed, out["content"])
+ }
+ if strings.Contains(streamed, "```") {
+ t.Fatalf("streamed fenced JSON %q", streamed)
+ }
+}
+
// TestGrounding_NoChunks: Cite=true but state has no chunks → no
// grounding call, status reflects "no_chunks".
func TestGrounding_NoChunks(t *testing.T) {
diff --git a/internal/agent/component/message.go b/internal/agent/component/message.go
index 1307c05fce..0ca8372d82 100644
--- a/internal/agent/component/message.go
+++ b/internal/agent/component/message.go
@@ -575,7 +575,6 @@ func formalizedContentFallback(inputs map[string]any) string {
if text, _ := inputs["formalized_content"].(string); strings.TrimSpace(text) != "" {
return text
}
-
return ""
}
diff --git a/internal/agent/component/message_test.go b/internal/agent/component/message_test.go
index 9f8d0b907f..83a722be04 100644
--- a/internal/agent/component/message_test.go
+++ b/internal/agent/component/message_test.go
@@ -354,6 +354,47 @@ func TestMessage_ConsumesDeferredAgentStream(t *testing.T) {
}
}
+func TestMessage_MaterializesDeferredAgentStructured(t *testing.T) {
+ c, _ := NewMessageComponent(nil)
+ state := canvas.NewCanvasState("run-deferred-structured", "task-deferred-structured")
+ opened := false
+ state.SetVar("Agent:HungryLiliesDance", "content", &runtime.DeferredStream{
+ Open: func(_ context.Context, _ runtime.AgentDeltaSink) (map[string]any, error) {
+ opened = true
+ return map[string]any{
+ "content": `{"findings":[{"ruleId":"r1"}],"opinion":{"conclusion":"PASS"}}`,
+ "structured": map[string]any{
+ "findings": []any{map[string]any{"ruleId": "r1"}},
+ "opinion": map[string]any{"conclusion": "PASS"},
+ },
+ }, nil
+ },
+ })
+ ctx := runtime.WithDeferredNodeRegistry(withStateForTest(t.Context(), state))
+ completed := false
+ runtime.RegisterDeferredNode(ctx, "Agent:HungryLiliesDance", func(error) { completed = true })
+
+ out, err := c.Invoke(ctx, nil, map[string]any{
+ "text": "{{Agent:HungryLiliesDance@structured}}",
+ })
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ if !opened {
+ t.Fatal("deferred Agent stream was not opened for @structured")
+ }
+ if !completed {
+ t.Fatal("deferred Agent node was not completed")
+ }
+ got, _ := out["content"].(string)
+ if !strings.Contains(got, `"findings"`) || !strings.Contains(got, `"ruleId":"r1"`) {
+ t.Fatalf("content = %q, want structured JSON", got)
+ }
+ if v, _ := state.GetVar("Agent:HungryLiliesDance@structured"); v == nil {
+ t.Fatal("structured missing from state after materialize")
+ }
+}
+
func TestMessage_DeferredStreamThinkingEvents(t *testing.T) {
c, _ := NewMessageComponent(nil)
state := canvas.NewCanvasState("run-deferred-thinking", "task-deferred-thinking")