Skip to main content

gadk_model/
aggregator.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Aggregation of streamed model responses: [`StreamingResponseAggregator`].
17
18use bytes::Bytes;
19use gadk_genai::{
20    CitationMetadata, Content, FinishReason, FunctionCall, GenerateContentResponse,
21    GenerateContentResponseUsageMetadata, GroundingMetadata, Part, PartialArg, ROLE_MODEL,
22};
23use serde_json::{Map, Value};
24
25use crate::convert::llm_response_from_genai;
26use crate::error::ModelError;
27use crate::jsonpath::{PathSegment, parse_json_path, set_value_by_path, value_by_path};
28use crate::llm::LlmResponse;
29
30/// Aggregates partial streaming responses: it yields an [`LlmResponse`] for every (partial)
31/// model response, and builds one aggregated response from their content, returned by
32/// [`close`](Self::close) once the stream ends. Text is buffered and merged, function calls
33/// whose arguments are streamed as JSON-path-addressed partial arguments are assembled, and
34/// thought signatures are propagated to the function call they belong to.
35#[derive(Debug, Default)]
36pub struct StreamingResponseAggregator {
37    usage_metadata: Option<GenerateContentResponseUsageMetadata>,
38    grounding_metadata: Option<GroundingMetadata>,
39    citation_metadata: Option<CitationMetadata>,
40    response: Option<LlmResponse>,
41
42    current_thought_signature: Option<Bytes>,
43
44    sequence: Vec<Part>,
45    current_text_buffer: String,
46    current_text_is_thought: bool,
47    /// The first thought signature streamed on a chunk of `current_text_buffer`, for the part
48    /// the buffer is flushed into. Unlike adk-python, the same signature is also still carried
49    /// forward to the next function call that has none (`current_thought_signature`), which
50    /// the turn history needs on Vertex AI.
51    current_text_signature: Option<Bytes>,
52    finish_reason: Option<FinishReason>,
53
54    current_function_name: String,
55    current_function_id: String,
56    current_function_args: Map<String, Value>,
57    current_function_thought_signature: Option<Bytes>,
58}
59
60impl StreamingResponseAggregator {
61    /// Creates an empty aggregator.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// Converts `resp` into an [`LlmResponse`] (marked partial), aggregates its content, and
67    /// returns the items to yield, in order. The returned items never contain an error today;
68    /// the `Result` leaves room for a future error.
69    pub fn process_response(
70        &mut self,
71        resp: GenerateContentResponse,
72    ) -> Vec<Result<LlmResponse, ModelError>> {
73        let mut llm_resp = llm_response_from_genai(&resp);
74        if let Some(candidate) = resp.candidates.first() {
75            llm_resp.turn_complete = candidate.finish_reason.is_some();
76        }
77        let mut out = Vec::with_capacity(2);
78        // Aggregate the response and check if an intermediate event to yield was created.
79        if let Some(aggr_resp) = self.aggregate_response(&mut llm_resp) {
80            out.push(Ok(aggr_resp));
81        }
82        // Yield the processed response.
83        out.push(Ok(llm_resp));
84        out
85    }
86
87    /// Folds `llm_response` into the aggregate state and marks it partial. It never produces an
88    /// intermediate response.
89    fn aggregate_response(&mut self, llm_response: &mut LlmResponse) -> Option<LlmResponse> {
90        if llm_response.usage_metadata.is_some() {
91            self.usage_metadata.clone_from(&llm_response.usage_metadata);
92        }
93        if llm_response.grounding_metadata.is_some() {
94            self.grounding_metadata
95                .clone_from(&llm_response.grounding_metadata);
96        }
97        if llm_response.citation_metadata.is_some() {
98            self.citation_metadata
99                .clone_from(&llm_response.citation_metadata);
100        }
101        if llm_response.finish_reason.is_some() {
102            self.finish_reason.clone_from(&llm_response.finish_reason);
103        }
104        llm_response.partial = true;
105
106        if let Some(content) = llm_response.content.as_mut() {
107            for part in &mut content.parts {
108                // Gemini 3 in streaming returns a last response with an empty part; filter it.
109                if *part == Part::default() {
110                    continue;
111                }
112                if !part.thought_signature.is_empty() {
113                    self.current_thought_signature = Some(part.thought_signature.clone());
114                }
115                if !part.text.is_empty() {
116                    if !self.current_text_buffer.is_empty()
117                        && part.thought != self.current_text_is_thought
118                    {
119                        self.flush_text_buffer_to_sequence();
120                    }
121                    if self.current_text_buffer.is_empty() {
122                        self.current_text_is_thought = part.thought;
123                    }
124                    self.current_text_buffer.push_str(&part.text);
125                    if !part.thought_signature.is_empty() && self.current_text_signature.is_none() {
126                        self.current_text_signature = Some(part.thought_signature.clone());
127                    }
128                } else if part.function_call.is_some() {
129                    // Handles both streaming (partial) and non-streaming args.
130                    self.process_function_call_part(part);
131                } else {
132                    // Other non-text parts (bytes, etc.): flush buffered text first.
133                    self.flush_text_buffer_to_sequence();
134                    self.sequence.push(part.clone());
135                }
136            }
137        }
138        // The response is stored before the loop above mutates its parts; storing the finished
139        // response here observes the same final state.
140        self.response = Some(llm_response.clone());
141        None
142    }
143
144    /// Takes `part` mutably because a propagated thought signature and a streamed
145    /// call's id are written into the part itself, which is also the part of the response
146    /// being yielded.
147    fn process_function_call_part(&mut self, part: &mut Part) {
148        let Some(fc) = part.function_call.as_mut() else {
149            return;
150        };
151        if !fc.partial_args.is_empty() || fc.will_continue == Some(true) {
152            if !part.thought_signature.is_empty()
153                && self.current_function_thought_signature.is_none()
154            {
155                self.current_function_thought_signature = Some(part.thought_signature.clone());
156            }
157            self.process_streaming_function_call_part(fc);
158        } else if fc.name.is_empty() {
159            // A nameless chunk continues the call being streamed, for example by only setting
160            // will_continue to false, so it carries that call's id.
161            if fc.id.is_empty() {
162                fc.id.clone_from(&self.current_function_id);
163            }
164        } else {
165            self.flush_text_buffer_to_sequence();
166            if part.thought_signature.is_empty()
167                && let Some(sig) = self.current_thought_signature.as_ref()
168            {
169                part.thought_signature = sig.clone();
170            }
171            self.current_thought_signature = None;
172            self.sequence.push(part.clone());
173        }
174    }
175
176    /// Processes a streaming function call carrying partial arguments. A chunk without an id
177    /// is given the streamed call's id, in the yielded part too.
178    fn process_streaming_function_call_part(&mut self, fc: &mut FunctionCall) {
179        if !fc.name.is_empty() {
180            self.current_function_name.clone_from(&fc.name);
181        }
182        if fc.id.is_empty() {
183            fc.id.clone_from(&self.current_function_id);
184        } else {
185            self.current_function_id.clone_from(&fc.id);
186        }
187        for arg in &fc.partial_args {
188            let Some(segments) = parse_json_path(&arg.json_path) else {
189                continue;
190            };
191            let Some(value) = self.get_value_from_partial_arg(arg, &segments) else {
192                continue;
193            };
194            set_value_by_path(&mut self.current_function_args, &segments, value);
195        }
196        if fc.will_continue == Some(true) {
197            return;
198        }
199        self.flush_text_buffer_to_sequence();
200        self.flush_function_call_to_sequence();
201    }
202
203    /// The value a partial argument carries, or `None` when it carries none. A string is
204    /// streamed in chunks that all carry the same path, so a string chunk is appended to
205    /// whatever of it has already been assembled.
206    fn get_value_from_partial_arg(
207        &self,
208        partial_arg: &PartialArg,
209        segments: &[PathSegment],
210    ) -> Option<Value> {
211        if !partial_arg.string_value.is_empty() {
212            let chunk = &partial_arg.string_value;
213            let value = match value_by_path(&self.current_function_args, segments) {
214                Some(Value::String(existing)) => format!("{existing}{chunk}"),
215                _ => chunk.clone(),
216            };
217            return Some(Value::String(value));
218        }
219        if let Some(n) = partial_arg.number_value {
220            // Non-finite numbers have no JSON representation, so they become JSON `null`.
221            return Some(serde_json::Number::from_f64(n).map_or(Value::Null, Value::Number));
222        }
223        if let Some(b) = partial_arg.bool_value {
224            return Some(Value::Bool(b));
225        }
226        if !partial_arg.null_value.is_empty() {
227            return Some(Value::Null);
228        }
229        None
230    }
231
232    /// Moves the buffered text, if any, into the sequence as one text part.
233    fn flush_text_buffer_to_sequence(&mut self) {
234        if !self.current_text_buffer.is_empty() {
235            self.sequence.push(Part {
236                text: std::mem::take(&mut self.current_text_buffer),
237                thought: self.current_text_is_thought,
238                thought_signature: self.current_text_signature.take().unwrap_or_default(),
239                ..Default::default()
240            });
241            self.current_text_is_thought = false;
242        }
243    }
244
245    /// Moves the pending function call, if any, into the sequence as one function-call part.
246    fn flush_function_call_to_sequence(&mut self) {
247        if !self.current_function_name.is_empty() {
248            let fc = FunctionCall {
249                name: std::mem::take(&mut self.current_function_name),
250                args: std::mem::take(&mut self.current_function_args),
251                id: std::mem::take(&mut self.current_function_id),
252                ..Default::default()
253            };
254            self.sequence.push(Part {
255                function_call: Some(fc),
256                thought_signature: self
257                    .current_function_thought_signature
258                    .take()
259                    .unwrap_or_default(),
260                ..Default::default()
261            });
262        }
263    }
264
265    /// Generates the aggregated response at the end of the stream, if any response was
266    /// processed. Call it after all the model responses are processed.
267    pub fn close(&mut self) -> Option<LlmResponse> {
268        let response = self.response.as_ref()?;
269        let (error_code, error_message) = if self.finish_reason == Some(FinishReason::Stop) {
270            (String::new(), String::new())
271        } else {
272            (response.error_code.clone(), response.error_message.clone())
273        };
274        let model_version = response.model_version.clone();
275        self.flush_text_buffer_to_sequence();
276        self.flush_function_call_to_sequence();
277        Some(LlmResponse {
278            content: Some(Content {
279                parts: self.sequence.clone(),
280                role: ROLE_MODEL.to_owned(),
281            }),
282            usage_metadata: self.usage_metadata.clone(),
283            grounding_metadata: self.grounding_metadata.clone(),
284            citation_metadata: self.citation_metadata.clone(),
285            error_code,
286            error_message,
287            finish_reason: self.finish_reason.clone(),
288            model_version,
289            ..Default::default()
290        })
291    }
292}