1use 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#[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 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 pub fn new() -> Self {
63 Self::default()
64 }
65
66 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 if let Some(aggr_resp) = self.aggregate_response(&mut llm_resp) {
80 out.push(Ok(aggr_resp));
81 }
82 out.push(Ok(llm_resp));
84 out
85 }
86
87 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 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 self.process_function_call_part(part);
131 } else {
132 self.flush_text_buffer_to_sequence();
134 self.sequence.push(part.clone());
135 }
136 }
137 }
138 self.response = Some(llm_response.clone());
141 None
142 }
143
144 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 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 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 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 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 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 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 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}