1use super::types::{A2aFileContent, A2aPart};
4use gemini_genai_rs::prelude::{
5 Blob, CodeExecutionResult, ExecutableCode, FunctionCall, FunctionResponse, Part,
6};
7use std::collections::HashMap;
8
9pub const ADK_TYPE_KEY: &str = "adk_type";
11pub const ADK_IS_LONG_RUNNING_KEY: &str = "adk_is_long_running";
13pub const ADK_THOUGHT_KEY: &str = "adk_thought";
15
16pub const DATA_TYPE_FUNCTION_CALL: &str = "function_call";
18pub const DATA_TYPE_FUNCTION_RESPONSE: &str = "function_response";
20pub const DATA_TYPE_CODE_EXEC_RESULT: &str = "code_execution_result";
22pub const DATA_TYPE_EXECUTABLE_CODE: &str = "executable_code";
24
25pub fn to_a2a_parts(parts: &[Part], long_running_tool_ids: &[String]) -> Vec<A2aPart> {
27 parts
28 .iter()
29 .filter_map(|p| to_a2a_part(p, long_running_tool_ids))
30 .collect()
31}
32
33pub fn to_a2a_part(part: &Part, long_running_tool_ids: &[String]) -> Option<A2aPart> {
35 match part {
36 Part::Text { text } => Some(A2aPart::Text {
37 text: text.clone(),
38 metadata: None,
39 }),
40 Part::InlineData { inline_data } => Some(A2aPart::File {
41 file: A2aFileContent {
42 name: None,
43 mime_type: Some(inline_data.mime_type.clone()),
44 bytes: Some(inline_data.data.clone()),
45 uri: None,
46 },
47 metadata: None,
48 }),
49 Part::FunctionCall { function_call } => {
50 let mut metadata = HashMap::new();
51 metadata.insert(
52 ADK_TYPE_KEY.to_string(),
53 serde_json::json!(DATA_TYPE_FUNCTION_CALL),
54 );
55 if let Some(id) = &function_call.id
56 && long_running_tool_ids.contains(id)
57 {
58 metadata.insert(ADK_IS_LONG_RUNNING_KEY.to_string(), serde_json::json!(true));
59 }
60 Some(A2aPart::Data {
61 data: serde_json::json!({
62 "name": function_call.name,
63 "args": function_call.args,
64 "id": function_call.id,
65 }),
66 metadata: Some(metadata),
67 })
68 }
69 Part::FunctionResponse { function_response } => {
70 let mut metadata = HashMap::new();
71 metadata.insert(
72 ADK_TYPE_KEY.to_string(),
73 serde_json::json!(DATA_TYPE_FUNCTION_RESPONSE),
74 );
75 Some(A2aPart::Data {
76 data: serde_json::json!({
77 "name": function_response.name,
78 "response": function_response.response,
79 "id": function_response.id,
80 }),
81 metadata: Some(metadata),
82 })
83 }
84 Part::ExecutableCode { executable_code } => {
85 let mut metadata = HashMap::new();
86 metadata.insert(
87 ADK_TYPE_KEY.to_string(),
88 serde_json::json!(DATA_TYPE_EXECUTABLE_CODE),
89 );
90 Some(A2aPart::Data {
91 data: serde_json::json!({
92 "language": executable_code.language,
93 "code": executable_code.code,
94 }),
95 metadata: Some(metadata),
96 })
97 }
98 Part::CodeExecutionResult {
99 code_execution_result,
100 } => {
101 let mut metadata = HashMap::new();
102 metadata.insert(
103 ADK_TYPE_KEY.to_string(),
104 serde_json::json!(DATA_TYPE_CODE_EXEC_RESULT),
105 );
106 Some(A2aPart::Data {
107 data: serde_json::json!({
108 "outcome": code_execution_result.outcome,
109 "output": code_execution_result.output,
110 }),
111 metadata: Some(metadata),
112 })
113 }
114 Part::Thought { text, .. } => Some(A2aPart::Text {
115 text: text.clone(),
116 metadata: None,
117 }),
118 }
119}
120
121pub fn to_genai_parts(a2a_parts: &[A2aPart]) -> Vec<Part> {
123 a2a_parts.iter().filter_map(to_genai_part).collect()
124}
125
126pub fn to_genai_part(a2a_part: &A2aPart) -> Option<Part> {
128 match a2a_part {
129 A2aPart::Text { text, .. } => Some(Part::Text { text: text.clone() }),
130 A2aPart::File { file, .. } => {
131 file.bytes.as_ref().map(|bytes| Part::InlineData {
133 inline_data: Blob {
134 mime_type: file.mime_type.clone().unwrap_or_default(),
135 data: bytes.clone(),
136 },
137 })
138 }
139 A2aPart::Data { data, metadata } => {
140 let adk_type = metadata
141 .as_ref()
142 .and_then(|m| m.get(ADK_TYPE_KEY))
143 .and_then(|v| v.as_str());
144
145 match adk_type {
146 Some(DATA_TYPE_FUNCTION_CALL) => Some(Part::FunctionCall {
147 function_call: FunctionCall {
148 name: data.get("name")?.as_str()?.to_string(),
149 args: data.get("args").cloned().unwrap_or(serde_json::json!({})),
150 id: data.get("id").and_then(|v| v.as_str()).map(String::from),
151 thought_signature: None,
152 },
153 }),
154 Some(DATA_TYPE_FUNCTION_RESPONSE) => Some(Part::FunctionResponse {
155 function_response: FunctionResponse {
156 name: data.get("name")?.as_str()?.to_string(),
157 response: data
158 .get("response")
159 .cloned()
160 .unwrap_or(serde_json::json!({})),
161 id: data.get("id").and_then(|v| v.as_str()).map(String::from),
162 scheduling: None,
163 },
164 }),
165 Some(DATA_TYPE_EXECUTABLE_CODE) => Some(Part::ExecutableCode {
166 executable_code: ExecutableCode {
167 language: data.get("language")?.as_str()?.to_string(),
168 code: data.get("code")?.as_str()?.to_string(),
169 },
170 }),
171 Some(DATA_TYPE_CODE_EXEC_RESULT) => Some(Part::CodeExecutionResult {
172 code_execution_result: CodeExecutionResult {
173 outcome: data.get("outcome")?.as_str()?.to_string(),
174 output: data
175 .get("output")
176 .and_then(|v| v.as_str())
177 .map(String::from),
178 },
179 }),
180 _ => None,
181 }
182 }
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn text_part_to_a2a() {
192 let part = Part::Text {
193 text: "hello world".to_string(),
194 };
195 let a2a = to_a2a_part(&part, &[]).unwrap();
196 match a2a {
197 A2aPart::Text { text, metadata } => {
198 assert_eq!(text, "hello world");
199 assert!(metadata.is_none());
200 }
201 _ => panic!("Expected Text part"),
202 }
203 }
204
205 #[test]
206 fn inline_data_to_a2a_file() {
207 let part = Part::InlineData {
208 inline_data: Blob {
209 mime_type: "image/png".to_string(),
210 data: "base64data".to_string(),
211 },
212 };
213 let a2a = to_a2a_part(&part, &[]).unwrap();
214 match a2a {
215 A2aPart::File { file, metadata } => {
216 assert_eq!(file.mime_type.as_deref(), Some("image/png"));
217 assert_eq!(file.bytes.as_deref(), Some("base64data"));
218 assert!(file.uri.is_none());
219 assert!(file.name.is_none());
220 assert!(metadata.is_none());
221 }
222 _ => panic!("Expected File part"),
223 }
224 }
225
226 #[test]
227 fn function_call_to_a2a_data_with_metadata() {
228 let part = Part::FunctionCall {
229 function_call: FunctionCall {
230 name: "get_weather".to_string(),
231 args: serde_json::json!({"city": "London"}),
232 id: Some("call-1".to_string()),
233 thought_signature: None,
234 },
235 };
236 let a2a = to_a2a_part(&part, &[]).unwrap();
237 match &a2a {
238 A2aPart::Data { data, metadata } => {
239 assert_eq!(data["name"], "get_weather");
240 assert_eq!(data["args"]["city"], "London");
241 assert_eq!(data["id"], "call-1");
242 let meta = metadata.as_ref().unwrap();
243 assert_eq!(meta[ADK_TYPE_KEY], DATA_TYPE_FUNCTION_CALL);
244 assert!(!meta.contains_key(ADK_IS_LONG_RUNNING_KEY));
245 }
246 _ => panic!("Expected Data part"),
247 }
248 }
249
250 #[test]
251 fn function_call_long_running() {
252 let part = Part::FunctionCall {
253 function_call: FunctionCall {
254 name: "slow_op".to_string(),
255 args: serde_json::json!({}),
256 id: Some("lr-1".to_string()),
257 thought_signature: None,
258 },
259 };
260 let long_running = vec!["lr-1".to_string()];
261 let a2a = to_a2a_part(&part, &long_running).unwrap();
262 match &a2a {
263 A2aPart::Data { metadata, .. } => {
264 let meta = metadata.as_ref().unwrap();
265 assert_eq!(meta[ADK_IS_LONG_RUNNING_KEY], serde_json::json!(true));
266 }
267 _ => panic!("Expected Data part"),
268 }
269 }
270
271 #[test]
272 fn function_response_to_a2a_data() {
273 let part = Part::FunctionResponse {
274 function_response: FunctionResponse {
275 name: "get_weather".to_string(),
276 response: serde_json::json!({"temp": 20}),
277 id: Some("call-1".to_string()),
278 scheduling: None,
279 },
280 };
281 let a2a = to_a2a_part(&part, &[]).unwrap();
282 match &a2a {
283 A2aPart::Data { data, metadata } => {
284 assert_eq!(data["name"], "get_weather");
285 assert_eq!(data["response"]["temp"], 20);
286 assert_eq!(data["id"], "call-1");
287 let meta = metadata.as_ref().unwrap();
288 assert_eq!(meta[ADK_TYPE_KEY], DATA_TYPE_FUNCTION_RESPONSE);
289 }
290 _ => panic!("Expected Data part"),
291 }
292 }
293
294 #[test]
295 fn executable_code_to_a2a_data() {
296 let part = Part::ExecutableCode {
297 executable_code: ExecutableCode {
298 language: "python".to_string(),
299 code: "print('hi')".to_string(),
300 },
301 };
302 let a2a = to_a2a_part(&part, &[]).unwrap();
303 match &a2a {
304 A2aPart::Data { data, metadata } => {
305 assert_eq!(data["language"], "python");
306 assert_eq!(data["code"], "print('hi')");
307 let meta = metadata.as_ref().unwrap();
308 assert_eq!(meta[ADK_TYPE_KEY], DATA_TYPE_EXECUTABLE_CODE);
309 }
310 _ => panic!("Expected Data part"),
311 }
312 }
313
314 #[test]
315 fn code_execution_result_to_a2a_data() {
316 let part = Part::CodeExecutionResult {
317 code_execution_result: CodeExecutionResult {
318 outcome: "success".to_string(),
319 output: Some("hi".to_string()),
320 },
321 };
322 let a2a = to_a2a_part(&part, &[]).unwrap();
323 match &a2a {
324 A2aPart::Data { data, metadata } => {
325 assert_eq!(data["outcome"], "success");
326 assert_eq!(data["output"], "hi");
327 let meta = metadata.as_ref().unwrap();
328 assert_eq!(meta[ADK_TYPE_KEY], DATA_TYPE_CODE_EXEC_RESULT);
329 }
330 _ => panic!("Expected Data part"),
331 }
332 }
333
334 #[test]
335 fn a2a_text_to_genai_part() {
336 let a2a = A2aPart::Text {
337 text: "hello".to_string(),
338 metadata: None,
339 };
340 let part = to_genai_part(&a2a).unwrap();
341 match part {
342 Part::Text { text } => assert_eq!(text, "hello"),
343 _ => panic!("Expected Text part"),
344 }
345 }
346
347 #[test]
348 fn a2a_file_to_genai_inline_data() {
349 let a2a = A2aPart::File {
350 file: A2aFileContent {
351 name: None,
352 mime_type: Some("audio/pcm".to_string()),
353 bytes: Some("pcmdata".to_string()),
354 uri: None,
355 },
356 metadata: None,
357 };
358 let part = to_genai_part(&a2a).unwrap();
359 match part {
360 Part::InlineData { inline_data } => {
361 assert_eq!(inline_data.mime_type, "audio/pcm");
362 assert_eq!(inline_data.data, "pcmdata");
363 }
364 _ => panic!("Expected InlineData part"),
365 }
366 }
367
368 #[test]
369 fn a2a_file_uri_only_returns_none() {
370 let a2a = A2aPart::File {
371 file: A2aFileContent {
372 name: None,
373 mime_type: Some("image/png".to_string()),
374 bytes: None,
375 uri: Some("gs://bucket/img.png".to_string()),
376 },
377 metadata: None,
378 };
379 assert!(to_genai_part(&a2a).is_none());
380 }
381
382 #[test]
383 fn a2a_data_function_call_to_genai() {
384 let mut metadata = HashMap::new();
385 metadata.insert(
386 ADK_TYPE_KEY.to_string(),
387 serde_json::json!(DATA_TYPE_FUNCTION_CALL),
388 );
389 let a2a = A2aPart::Data {
390 data: serde_json::json!({
391 "name": "search",
392 "args": {"query": "rust"},
393 "id": "fc-1",
394 }),
395 metadata: Some(metadata),
396 };
397 let part = to_genai_part(&a2a).unwrap();
398 match part {
399 Part::FunctionCall { function_call } => {
400 assert_eq!(function_call.name, "search");
401 assert_eq!(function_call.args["query"], "rust");
402 assert_eq!(function_call.id.as_deref(), Some("fc-1"));
403 }
404 _ => panic!("Expected FunctionCall part"),
405 }
406 }
407
408 #[test]
409 fn a2a_data_function_response_to_genai() {
410 let mut metadata = HashMap::new();
411 metadata.insert(
412 ADK_TYPE_KEY.to_string(),
413 serde_json::json!(DATA_TYPE_FUNCTION_RESPONSE),
414 );
415 let a2a = A2aPart::Data {
416 data: serde_json::json!({
417 "name": "search",
418 "response": {"results": [1, 2, 3]},
419 "id": "fc-1",
420 }),
421 metadata: Some(metadata),
422 };
423 let part = to_genai_part(&a2a).unwrap();
424 match part {
425 Part::FunctionResponse { function_response } => {
426 assert_eq!(function_response.name, "search");
427 assert_eq!(
428 function_response.response["results"],
429 serde_json::json!([1, 2, 3])
430 );
431 assert_eq!(function_response.id.as_deref(), Some("fc-1"));
432 }
433 _ => panic!("Expected FunctionResponse part"),
434 }
435 }
436
437 #[test]
438 fn a2a_data_executable_code_to_genai() {
439 let mut metadata = HashMap::new();
440 metadata.insert(
441 ADK_TYPE_KEY.to_string(),
442 serde_json::json!(DATA_TYPE_EXECUTABLE_CODE),
443 );
444 let a2a = A2aPart::Data {
445 data: serde_json::json!({
446 "language": "python",
447 "code": "x = 1",
448 }),
449 metadata: Some(metadata),
450 };
451 let part = to_genai_part(&a2a).unwrap();
452 match part {
453 Part::ExecutableCode { executable_code } => {
454 assert_eq!(executable_code.language, "python");
455 assert_eq!(executable_code.code, "x = 1");
456 }
457 _ => panic!("Expected ExecutableCode part"),
458 }
459 }
460
461 #[test]
462 fn a2a_data_code_exec_result_to_genai() {
463 let mut metadata = HashMap::new();
464 metadata.insert(
465 ADK_TYPE_KEY.to_string(),
466 serde_json::json!(DATA_TYPE_CODE_EXEC_RESULT),
467 );
468 let a2a = A2aPart::Data {
469 data: serde_json::json!({
470 "outcome": "success",
471 "output": "42",
472 }),
473 metadata: Some(metadata),
474 };
475 let part = to_genai_part(&a2a).unwrap();
476 match part {
477 Part::CodeExecutionResult {
478 code_execution_result,
479 } => {
480 assert_eq!(code_execution_result.outcome, "success");
481 assert_eq!(code_execution_result.output.as_deref(), Some("42"));
482 }
483 _ => panic!("Expected CodeExecutionResult part"),
484 }
485 }
486
487 #[test]
488 fn a2a_data_unknown_type_returns_none() {
489 let a2a = A2aPart::Data {
490 data: serde_json::json!({"foo": "bar"}),
491 metadata: None,
492 };
493 assert!(to_genai_part(&a2a).is_none());
494 }
495
496 #[test]
499 fn round_trip_text() {
500 let original = Part::Text {
501 text: "round trip".to_string(),
502 };
503 let a2a = to_a2a_part(&original, &[]).unwrap();
504 let back = to_genai_part(&a2a).unwrap();
505 assert_eq!(back, original);
506 }
507
508 #[test]
509 fn round_trip_function_call() {
510 let original = Part::FunctionCall {
511 function_call: FunctionCall {
512 name: "my_tool".to_string(),
513 args: serde_json::json!({"x": 10}),
514 id: Some("id-1".to_string()),
515 thought_signature: None,
516 },
517 };
518 let a2a = to_a2a_part(&original, &[]).unwrap();
519 let back = to_genai_part(&a2a).unwrap();
520 assert_eq!(back, original);
521 }
522
523 #[test]
524 fn round_trip_function_response() {
525 let original = Part::FunctionResponse {
526 function_response: FunctionResponse {
527 name: "my_tool".to_string(),
528 response: serde_json::json!({"result": "ok"}),
529 id: Some("id-1".to_string()),
530 scheduling: None,
531 },
532 };
533 let a2a = to_a2a_part(&original, &[]).unwrap();
534 let back = to_genai_part(&a2a).unwrap();
535 assert_eq!(back, original);
536 }
537
538 #[test]
539 fn to_a2a_parts_filters_and_collects() {
540 let parts = vec![
541 Part::Text {
542 text: "a".to_string(),
543 },
544 Part::Text {
545 text: "b".to_string(),
546 },
547 ];
548 let a2a = to_a2a_parts(&parts, &[]);
549 assert_eq!(a2a.len(), 2);
550 }
551
552 #[test]
553 fn to_genai_parts_filters_and_collects() {
554 let a2a_parts = vec![
555 A2aPart::Text {
556 text: "x".to_string(),
557 metadata: None,
558 },
559 A2aPart::Data {
561 data: serde_json::json!({}),
562 metadata: None,
563 },
564 ];
565 let genai = to_genai_parts(&a2a_parts);
566 assert_eq!(genai.len(), 1);
567 }
568}