@@ -73,6 +73,13 @@ func (a *Agent) GenerateStream(ctx context.Context, sessionID, userInput string)
7373
7474 // 3. Chain Orchestrator
7575 if handled , output , err := a .codeChainOrchestrator (ctx , sessionID , userInput ); handled {
76+ if err == nil && a .Guardrails != nil {
77+ validated , gErr := a .Guardrails .ValidateAndRepair (ctx , output )
78+ if gErr != nil {
79+ return immediateStream ("" , gErr )
80+ }
81+ output = validated
82+ }
7683 return immediateStream (output , err )
7784 }
7885
@@ -110,23 +117,51 @@ func (a *Agent) GenerateStream(ctx context.Context, sessionID, userInput string)
110117
111118 // Wrap the stream to intercept and store memory
112119 outCh := make (chan models.StreamChunk )
113- go func () {
114- defer close (outCh )
115- var full strings.Builder
116- for chunk := range stream {
117- if chunk .Err != nil {
118- outCh <- chunk
120+
121+ if a .Guardrails != nil {
122+ go func () {
123+ defer close (outCh )
124+ var full strings.Builder
125+ for chunk := range stream {
126+ if chunk .Err != nil {
127+ outCh <- chunk
128+ return
129+ }
130+ if chunk .Delta != "" {
131+ full .WriteString (chunk .Delta )
132+ }
133+ }
134+
135+ finalText := full .String ()
136+ validatedText , gErr := a .Guardrails .ValidateAndRepair (ctx , finalText )
137+ if gErr != nil {
138+ outCh <- models.StreamChunk {Err : gErr , Done : true }
119139 return
120140 }
121- if chunk .Delta != "" {
122- full .WriteString (chunk .Delta )
141+
142+ // Stream out the validated text as one chunk
143+ outCh <- models.StreamChunk {Delta : validatedText , FullText : validatedText , Done : true }
144+ a .storeMemory (sessionID , "assistant" , validatedText , nil )
145+ }()
146+ } else {
147+ go func () {
148+ defer close (outCh )
149+ var full strings.Builder
150+ for chunk := range stream {
151+ if chunk .Err != nil {
152+ outCh <- chunk
153+ return
154+ }
155+ if chunk .Delta != "" {
156+ full .WriteString (chunk .Delta )
157+ }
158+ outCh <- chunk
123159 }
124- outCh <- chunk
125- }
126- // Store memory after completion
127- finalText := full .String ()
128- a .storeMemory (sessionID , "assistant" , finalText , nil )
129- }()
160+ // Store memory after completion
161+ finalText := full .String ()
162+ a .storeMemory (sessionID , "assistant" , finalText , nil )
163+ }()
164+ }
130165
131166 return outCh , nil
132167}
0 commit comments