api_gemini 0.5.0

Gemini's API for accessing large language models (LLMs).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281

//! Comprehensive Function Calling & Tool Integration Example
//!
//! This example demonstrates advanced AI agent capabilities including:
//! - Dynamic function/tool registration and execution
//! - Multi-step workflow orchestration
//! - External API integration simulation
//! - Security controls and validation
//! - Comprehensive error handling and logging
//! - Interactive and automated execution modes
//!
//! Usage:
//! ```bash
//! # Interactive mode with specific tools
//! cargo run --example gemini_function_calling -- --agent-mode interactive --tools weather,calculator,search
//!
//! # Execute specific task with all tools
//! cargo run --example gemini_function_calling -- --task "Plan a trip to Paris" --use-tools all
//!
//! # API integration demo
//! cargo run --example gemini_function_calling -- --demo api_integration --service weather_api
//! ```

use api_gemini::{ client::Client, models::* };
use serde_json::{ json, Value };
use std::collections::HashMap;
use std::env;
use std::time::{ Duration, Instant };
use tokio::time::timeout;

/// Configuration for the AI agent
#[ derive( Debug, Clone ) ]
pub struct AgentConfig
{
  /// Agent execution mode
  pub agent_mode: AgentMode,
  /// List of available tools for the agent
  pub available_tools: Vec< String >,
  /// Task description for automated mode
  pub task_description: Option< String >,
  /// Service name for demo mode
  pub demo_service: Option< String >,
  /// Maximum number of workflow iterations
  pub max_iterations: usize,
  /// Function timeout in seconds
  pub timeout_seconds: u64,
  /// Enable detailed logging
  pub logging_enabled: bool,
}

/// Agent execution mode
#[ derive( Debug, Clone ) ]
pub enum AgentMode
{
  /// Interactive mode with user input
  Interactive,
  /// Automated mode with predefined task
  Automated,
  /// Demo mode with predefined scenarios
  Demo( String ),
}

impl Default for AgentConfig
{
  fn default() -> Self
  {
    Self
    {
      agent_mode: AgentMode::Interactive,
      available_tools: vec![ "weather".to_string(), "calculator".to_string() ],
      task_description: None,
      demo_service: None,
      max_iterations: 10,
      timeout_seconds: 30,
      logging_enabled: true,
    }
  }
}

/// Function execution context with security and logging
#[ derive( Debug ) ]
pub struct FunctionContext
{
  /// Name of the executed function
  pub function_name: String,
  /// Arguments passed to the function
  pub arguments: Value,
  /// When function execution started
  pub execution_time: Instant,
  /// Maximum execution time allowed
  pub timeout: Duration,
  /// Whether parameter validation passed
  pub validation_passed: bool,
}

impl FunctionContext
{
  /// Create new function execution context
  pub fn new( name: String, args: Value, timeout_secs: u64 ) -> Self
  {
    Self
    {
      function_name: name,
      arguments: args,
      execution_time: Instant::now(),
      timeout: Duration::from_secs( timeout_secs ),
      validation_passed: false,
    }
  }

  /// Get elapsed execution time
  pub fn elapsed( &self ) -> Duration
  {
    self.execution_time.elapsed()
  }
}

/// Comprehensive tool registry with built-in functions
#[ derive( Debug ) ]
pub struct ToolRegistry
{
  available_functions: HashMap<  String, FunctionDeclaration  >,
  execution_log: Vec< FunctionContext >,
}

impl ToolRegistry
{
  /// Create new tool registry with default tools
  pub fn new() -> Self
  {
    let mut registry = Self
    {
      available_functions: HashMap::new(),
      execution_log: Vec::new(),
    };

    registry.register_default_tools();
    registry
  }

  fn register_default_tools( &mut self )
  {
    // Weather API tool
    self.available_functions.insert(
    "get_weather".to_string(),
    FunctionDeclaration
    {
      name: "get_weather".to_string(),
      description: "Get current weather conditions for a specific location".to_string(),
      parameters : Some( json!({
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "City name or location (e.g., 'San Francisco', 'Tokyo')"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"],
            "description": "Temperature unit preference",
            "default": "celsius"
          }
        },
        "required": ["location"]
      })),
    }
    );

    // Calculator tool
    self.available_functions.insert(
    "calculate".to_string(),
    FunctionDeclaration
    {
      name: "calculate".to_string(),
      description: "Perform mathematical calculations with support for basic arithmetic, percentages, and common functions".to_string(),
      parameters : Some( json!({
        "type": "object",
        "properties": {
          "expression": {
            "type": "string",
            "description": "Mathematical expression to evaluate (e.g., '2 + 3 * 4', 'sqrt(16)', '15% of 200')"
          },
          "precision": {
            "type": "integer",
            "description": "Number of decimal places for the result",
            "default": 2,
            "minimum": 0,
            "maximum": 10
          }
        },
        "required": ["expression"]
      })),
    }
    );

    // Search tool
    self.available_functions.insert(
    "web_search".to_string(),
    FunctionDeclaration
    {
      name: "web_search".to_string(),
      description: "Search the web for information on a specific topic or query".to_string(),
      parameters : Some( json!({
        "type": "object",
        "properties": {
          "query": {
            "type": "string",
            "description": "Search query or keywords"
          },
          "max_results": {
            "type": "integer",
            "description": "Maximum number of search results to return",
            "default": 5,
            "minimum": 1,
            "maximum": 20
          },
          "language": {
            "type": "string",
            "description": "Preferred language for results",
            "default": "en"
          }
        },
        "required": ["query"]
      })),
    }
    );

    // Flight search tool
    self.available_functions.insert(
    "search_flights".to_string(),
    FunctionDeclaration
    {
      name: "search_flights".to_string(),
      description: "Search for available flights between two locations".to_string(),
      parameters : Some( json!({
        "type": "object",
        "properties": {
          "from": {
            "type": "string",
            "description": "Departure city or airport code"
          },
          "to": {
            "type": "string",
            "description": "Arrival city or airport code"
          },
          "date": {
            "type": "string",
            "description": "Flight date in YYYY-MM-DD format"
          },
          "passengers": {
            "type": "integer",
            "description": "Number of passengers",
            "default": 1,
            "minimum": 1,
            "maximum": 9
          },
          "class": {
            "type": "string",
            "enum": ["economy", "business", "first"],
            "description": "Flight class preference",
            "default": "economy"
          }
        },
        "required": ["from", "to", "date"]
      })),
    }
    );

    // Database query tool
    self.available_functions.insert(
    "query_database".to_string(),
    FunctionDeclaration
    {
      name: "query_database".to_string(),
      description: "Execute queries against a simulated database for user data, orders, or analytics".to_string(),
      parameters : Some( json!({
        "type": "object",
        "properties": {
          "query_type": {
            "type": "string",
            "enum": ["users", "orders", "analytics", "inventory"],
            "description": "Type of data to query"
          },
          "filters": {
            "type": "object",
            "description": "Query filters and conditions"
          },
          "limit": {
            "type": "integer",
            "description": "Maximum number of results",
            "default": 10,
            "minimum": 1,
            "maximum": 100
          }
        },
        "required": ["query_type"]
      })),
    }
    );
  }

  /// Get tools filtered by name list
  pub fn get_tools_for_names( &self, tool_names: &[ String ] ) -> Vec< Tool >
  {
    let mut function_declarations = Vec::new();

    for tool_name in tool_names
    {
      if let Some( func_decl ) = self.available_functions.get( tool_name )
      {
        function_declarations.push( func_decl.clone() );
      }
    }

    if function_declarations.is_empty()
    {
      Vec::new() // Return empty vec if no functions
    }
    else
    {
      vec!
      [
      Tool
      {
        function_declarations: Some( function_declarations ),
        code_execution: None,
        google_search_retrieval: None,
        code_execution_tool: None,
      }
      ]
    }
  }

  /// Get all available tools
  pub fn get_all_tools( &self ) -> Vec< Tool >
  {
    let function_declarations: Vec< FunctionDeclaration > = self.available_functions
    .values()
    .cloned()
    .collect();

    if function_declarations.is_empty()
    {
      Vec::new() // Return empty vec if no functions
    }
    else
    {
      vec!
      [
      Tool
      {
        function_declarations: Some( function_declarations ),
        code_execution: None,
        google_search_retrieval: None,
        code_execution_tool: None,
      }
      ]
    }
  }

  /// Execute function with validation and logging
  pub async fn execute_function( &mut self, name: &str, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    let mut context = FunctionContext::new( name.to_string(), args.clone(), 30 );

    // Validate function exists
    if !self.available_functions.contains_key( name )
    {
    return Err( format!( "Function '{}' not found in registry", name ).into() );
    }

    // Validate parameters (basic validation)
    context.validation_passed = self.validate_parameters( name, args )?;

    // Execute with timeout
    let result = timeout( context.timeout, self.execute_function_impl( name, args ) ).await
.map_err( |_| format!( "Function '{}' timed out after {} seconds", name, context.timeout.as_secs() ) )?;

    // Log execution
    self.execution_log.push( context );

    result
  }

  fn validate_parameters( &self, name: &str, args: &Value ) -> Result< bool, Box< dyn std::error::Error > >
  {
    let func_decl = self.available_functions.get( name )
  .ok_or( format!( "Function '{}' not found", name ) )?;

    if let Some( schema ) = &func_decl.parameters
    {
      if let Some( required ) = schema.get( "required" ).and_then( |r| r.as_array() )
      {
        for req_field in required
        {
          if let Some( field_name ) = req_field.as_str()
          {
            if !args.get( field_name ).is_some()
            {
          return Err( format!( "Required parameter '{}' missing for function '{}'", field_name, name ).into() );
            }
          }
        }
      }
    }

    Ok( true )
  }

  async fn execute_function_impl( &self, name: &str, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    match name
    {
      "get_weather" => self.execute_weather( args ).await,
      "calculate" => self.execute_calculator( args ).await,
      "web_search" => self.execute_web_search( args ).await,
      "search_flights" => self.execute_flight_search( args ).await,
      "query_database" => self.execute_database_query( args ).await,
    _ => Err( format!( "Unknown function : {}", name ).into() ),
    }
  }

  async fn execute_weather( &self, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    let location = args.get( "location" )
    .and_then( |l| l.as_str() )
    .ok_or( "Missing location parameter" )?;

    let unit = args.get( "unit" )
    .and_then( |u| u.as_str() )
    .unwrap_or( "celsius" );

    // Simulate API call delay
    tokio ::time::sleep( Duration::from_millis( 100 ) ).await;

    // Simulated weather data with more comprehensive information
    let weather_data: HashMap<  &str, ( f32, &str, u8, f32, &str )  > = HashMap::from([
    ( "Tokyo", ( 22.0, "Partly cloudy", 65, 15.5, "Light breeze from southeast" ) ),
    ( "London", ( 15.0, "Rainy", 85, 18.0, "Moderate rain with strong winds" ) ),
    ( "New York", ( 18.0, "Sunny", 55, 12.0, "Clear skies with light winds" ) ),
    ( "Paris", ( 20.0, "Overcast", 70, 14.0, "Cloudy with occasional sun breaks" ) ),
    ( "Sydney", ( 25.0, "Clear", 45, 8.0, "Bright sunshine with calm conditions" ) ),
    ]);

    let ( temp, condition, humidity, wind_speed, description ) = weather_data
    .get( location )
    .unwrap_or( &( 20.0, "Unknown conditions", 50, 10.0, "Weather data unavailable" ) );

    let temp_converted = match unit
    {
      "fahrenheit" => temp * 9.0 / 5.0 + 32.0,
      _ => *temp,
    };

    Ok( json!({
      "location": location,
      "temperature": temp_converted,
      "unit": unit,
      "condition": condition,
      "humidity": humidity,
      "wind_speed": wind_speed,
      "description": description,
      "timestamp": "2024-01-15T10:00:00Z",
      "source": "WeatherAPI Simulation"
    }))
  }

  async fn execute_calculator( &self, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    let expression = args.get( "expression" )
    .and_then( |e| e.as_str() )
    .ok_or( "Missing expression parameter" )?;

    let precision = args.get( "precision" )
    .and_then( |p| p.as_u64() )
    .unwrap_or( 2 ) as usize;

    // Simulate calculation processing
    tokio ::time::sleep( Duration::from_millis( 50 ) ).await;

    // Simple expression evaluator (for demo purposes)
    let result = self.evaluate_expression( expression )?;

    Ok( json!({
      "expression": expression,
    "result": format!( "{:.1$}", result, precision ),
      "precision": precision,
      "calculation_time": "0.001s",
      "status": "success"
    }))
  }

  fn evaluate_expression( &self, expr: &str ) -> Result< f64, Box< dyn std::error::Error > >
  {
    // Basic calculator implementation for demo
    match expr.trim()
    {
      e if e.contains( "+" ) =>
      {
        let parts: Vec< &str > = e.split( '+' ).collect();
        if parts.len() == 2
        {
          let a: f64 = parts[ 0 ].trim().parse()?;
          let b: f64 = parts[ 1 ].trim().parse()?;
          Ok( a + b )
        }
        else
        {
          Err( "Invalid addition expression".into() )
        }
      }
      e if e.contains( "-" ) =>
      {
        let parts: Vec< &str > = e.split( '-' ).collect();
        if parts.len() == 2
        {
          let a: f64 = parts[ 0 ].trim().parse()?;
          let b: f64 = parts[ 1 ].trim().parse()?;
          Ok( a - b )
        }
        else
        {
          Err( "Invalid subtraction expression".into() )
        }
      }
      e if e.contains( "*" ) =>
      {
        let parts: Vec< &str > = e.split( '*' ).collect();
        if parts.len() == 2
        {
          let a: f64 = parts[ 0 ].trim().parse()?;
          let b: f64 = parts[ 1 ].trim().parse()?;
          Ok( a * b )
        }
        else
        {
          Err( "Invalid multiplication expression".into() )
        }
      }
      e if e.contains( "/" ) =>
      {
        let parts: Vec< &str > = e.split( '/' ).collect();
        if parts.len() == 2
        {
          let a: f64 = parts[ 0 ].trim().parse()?;
          let b: f64 = parts[ 1 ].trim().parse()?;
          if b == 0.0
          {
            Err( "Division by zero".into() )
          }
          else
          {
            Ok( a / b )
          }
        }
        else
        {
          Err( "Invalid division expression".into() )
        }
      }
      e if e.starts_with( "sqrt(" ) && e.ends_with( ')' ) =>
      {
        let num_str = &e[ 5..e.len() - 1 ];
        let num: f64 = num_str.parse()?;
        if num < 0.0
        {
          Err( "Cannot take square root of negative number".into() )
        }
        else
        {
          Ok( num.sqrt() )
        }
      }
      e if e.contains( "% of " ) =>
      {
        let parts: Vec< &str > = e.split( "% of " ).collect();
        if parts.len() == 2
        {
          let percentage: f64 = parts[ 0 ].trim().parse()?;
          let base: f64 = parts[ 1 ].trim().parse()?;
          Ok( ( percentage / 100.0 ) * base )
        }
        else
        {
          Err( "Invalid percentage expression".into() )
        }
      }
      e =>
      {
        // Try to parse as simple number
        match e.parse::< f64 >()
        {
          Ok( num ) => Ok( num ),
        Err( _ ) => Err( format!( "Unsupported expression : {}", e ).into() ),
        }
      }
    }
  }

  async fn execute_web_search( &self, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    let query = args.get( "query" )
    .and_then( |q| q.as_str() )
    .ok_or( "Missing query parameter" )?;

    let max_results = args.get( "max_results" )
    .and_then( |m| m.as_u64() )
    .unwrap_or( 5 ) as usize;

    // Simulate search API delay
    tokio ::time::sleep( Duration::from_millis( 200 ) ).await;

    // Simulated search results
    let mut results = Vec::new();
    for i in 1..=max_results.min( 10 )
    {
      results.push( json!({
    "title": format!( "Search Result {} for '{}'", i, query ),
      "url": format!( "https://example{}.com/search-results", i ),
      "snippet": format!( "This is a simulated search result snippet for query '{}'. Contains relevant information about the topic.", query ),
        "relevance_score": 0.9 - ( i as f64 * 0.1 )
      }));
    }

    Ok( json!({
      "query": query,
      "total_results": results.len(),
      "results": results,
      "search_time": "0.2s",
      "source": "WebSearch API Simulation"
    }))
  }

  async fn execute_flight_search( &self, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    let from = args.get( "from" )
    .and_then( |f| f.as_str() )
    .ok_or( "Missing from parameter" )?;

    let to = args.get( "to" )
    .and_then( |t| t.as_str() )
    .ok_or( "Missing to parameter" )?;

    let date = args.get( "date" )
    .and_then( |d| d.as_str() )
    .ok_or( "Missing date parameter" )?;

    let passengers = args.get( "passengers" )
    .and_then( |p| p.as_u64() )
    .unwrap_or( 1 );

    let class = args.get( "class" )
    .and_then( |c| c.as_str() )
    .unwrap_or( "economy" );

    // Simulate flight search API delay
    tokio ::time::sleep( Duration::from_millis( 300 ) ).await;

    let base_price = match ( from, to )
    {
      ( from, to ) if from.contains( "New York" ) && to.contains( "Tokyo" ) => 850.0,
      ( from, to ) if from.contains( "London" ) && to.contains( "Paris" ) => 180.0,
      _ => 450.0,
    };

    let class_multiplier = match class
    {
      "business" => 2.5,
      "first" => 4.0,
      _ => 1.0,
    };

    let flights = vec![
    json!({
      "flight_number": "AA123",
      "airline": "American Airlines",
      "departure": from,
      "arrival": to,
      "date": date,
      "departure_time": "08:00",
      "arrival_time": "22:30",
      "duration": "14h 30m",
      "price": (base_price * class_multiplier * passengers as f64) as u32,
      "class": class,
      "passengers": passengers,
      "stops": 1,
      "available_seats": 24
    }),
    json!({
      "flight_number": "UA456",
      "airline": "United Airlines",
      "departure": from,
      "arrival": to,
      "date": date,
      "departure_time": "14:00",
      "arrival_time": "04:30+1",
      "duration": "15h 30m",
      "price": ((base_price - 50.0) * class_multiplier * passengers as f64) as u32,
      "class": class,
      "passengers": passengers,
      "stops": 0,
      "available_seats": 18
    })
    ];

    Ok( json!({
      "search_params": {
        "from": from,
        "to": to,
        "date": date,
        "passengers": passengers,
        "class": class
      },
      "flights": flights,
      "search_time": "0.3s",
      "source": "FlightSearch API Simulation"
    }))
  }

  async fn execute_database_query( &self, args: &Value ) -> Result< Value, Box< dyn std::error::Error > >
  {
    let query_type = args.get( "query_type" )
    .and_then( |q| q.as_str() )
    .ok_or( "Missing query_type parameter" )?;

    let limit = args.get( "limit" )
    .and_then( |l| l.as_u64() )
    .unwrap_or( 10 ) as usize;

    // Simulate database query delay
    tokio ::time::sleep( Duration::from_millis( 150 ) ).await;

    let data = match query_type
    {
      "users" => json!({
        "total_count": 1250,
        "data": (1..=limit.min( 5 )).map( |i| json!({
          "user_id": i,
        "name": format!( "User {}", i ),
        "email": format!( "user{}@example.com", i ),
          "created_at": "2024-01-15T10:00:00Z",
          "status": "active"
        })).collect::< Vec< _ > >()
      }),
      "orders" => json!({
        "total_count": 5420,
        "data": (1..=limit.min( 5 )).map( |i| json!({
        "order_id": format!( "ORD-{:06}", i ),
          "customer_id": i,
          "amount": 150.00 + ( i as f64 * 25.0 ),
          "status": "completed",
          "created_at": "2024-01-15T10:00:00Z"
        })).collect::< Vec< _ > >()
      }),
      "analytics" => json!({
        "metrics": {
          "daily_revenue": 12500.00,
          "active_users": 850,
          "conversion_rate": 3.2,
          "avg_order_value": 185.50
        },
        "trends": {
          "revenue_growth": "+15%",
          "user_growth": "+8%",
          "conversion_trend": "stable"
        }
      }),
      "inventory" => json!({
        "total_items": 850,
        "data": (1..=limit.min( 5 )).map( |i| json!({
        "product_id": format!( "PROD-{:04}", i ),
        "name": format!( "Product {}", i ),
          "stock_quantity": 50 + i * 10,
          "price": 25.00 + ( i as f64 * 5.0 ),
          "category": "electronics"
        })).collect::< Vec< _ > >()
      }),
    _ => return Err( format!( "Unknown query type : {}", query_type ).into() ),
    };

    Ok( json!({
      "query_type": query_type,
      "execution_time": "0.15s",
      "result": data,
      "source": "Database Simulation"
    }))
  }

  /// Get execution statistics summary
  pub fn get_execution_summary( &self ) -> Value
  {
    json!({
      "total_executions": self.execution_log.len(),
      "functions_used": self.execution_log.iter()
      .map( |ctx| ctx.function_name.clone() )
      .collect::< std::collections::HashSet<  _  > >()
      .into_iter()
      .collect::< Vec< _ > >(),
      "average_execution_time": if self.execution_log.is_empty()
      {
        0.0
      } else {
        self.execution_log.iter()
        .map( |ctx| ctx.elapsed().as_secs_f64() )
        .sum::< f64 >() / self.execution_log.len() as f64
      },
      "validation_success_rate": if self.execution_log.is_empty()
      {
        100.0
      } else {
        self.execution_log.iter()
        .filter( |ctx| ctx.validation_passed )
        .count() as f64 / self.execution_log.len() as f64 * 100.0
      }
    })
  }
}

/// AI Agent that can execute multi-step workflows
#[ derive( Debug ) ]
pub struct FunctionCallingAgent
{
  client: Client,
  tool_registry: ToolRegistry,
  config: AgentConfig,
  conversation_history: Vec< Content >,
}

impl FunctionCallingAgent
{
  /// Create new function calling agent
  pub fn new( config: AgentConfig ) -> Result< Self, Box< dyn std::error::Error > >
  {
    Ok( Self
    {
      client: Client::new()?,
      tool_registry: ToolRegistry::new(),
      config,
      conversation_history: Vec::new(),
    })
  }

  /// Execute task using available tools
  pub async fn execute_task( &mut self, task: &str ) -> Result< String, Box< dyn std::error::Error > >
  {
    if self.config.logging_enabled
    {
    println!( "Starting task execution : '{}'", task );
    println!( "Available tools : {:?}", self.config.available_tools );
    }

    // Initialize conversation
    self.conversation_history.clear();
    self.conversation_history.push( Content
    {
      role: "user".to_string(),
      parts: vec![ Part
      {
      text : Some( format!( "{} Please use the available tools to get accurate, up-to-date information.", task ) ),
        inline_data: None,
        function_call: None,
        function_response: None,
        ..Default::default()
      }],
    });

    let mut iteration = 0;
    let mut final_response = String::new();

    while iteration < self.config.max_iterations
    {
      iteration += 1;

      if self.config.logging_enabled
      {
    println!( "\nIteration {}/{}", iteration, self.config.max_iterations );
      }

      let tools = if self.config.available_tools.contains( &"all".to_string() )
      {
        self.tool_registry.get_all_tools()
      }
      else
      {
        self.tool_registry.get_tools_for_names( &self.config.available_tools )
      };

      let request = GenerateContentRequest
      {
        contents: self.conversation_history.clone(),
        generation_config: Some( GenerationConfig
        {
          temperature: Some( 0.1 ), // Low temperature for reliable function calling
          top_k: Some( 40 ),
          top_p: Some( 0.95 ),
          candidate_count: Some( 1 ),
          max_output_tokens: Some( 2048 ),
          stop_sequences: None,
        }),
        safety_settings: None,
        tools: Some( tools ),
        tool_config: None,
        system_instruction: None,
        cached_content: None,
      };

      let response = timeout(
      Duration::from_secs( self.config.timeout_seconds ),
      self.client.models().by_name( "gemini-2.5-flash" ).generate_content( &request )
      ).await??;

      if let Some( candidate ) = response.candidates.first()
      {
        // Add model's response to conversation
        self.conversation_history.push( candidate.content.clone() );

        let mut has_function_calls = false;
        let mut function_responses = Vec::new();

        // Process function calls
        for part in &candidate.content.parts
        {
          if let Some( function_call ) = &part.function_call
          {
            has_function_calls = true;

            if self.config.logging_enabled
            {
          println!( "Function call : {} with args : {}", 
              function_call.name, 
              serde_json ::to_string_pretty( &function_call.args )? 
              );
            }

            match self.tool_registry.execute_function( &function_call.name, &function_call.args ).await
            {
              Ok( result ) =>
              {
                if self.config.logging_enabled
                {
                println!( "Function result : {}", serde_json::to_string_pretty( &result )? );
                }

                function_responses.push( Part
                {
                  text: None,
                  inline_data: None,
                  function_call: None,
                  function_response: Some( FunctionResponse
                  {
                    name: function_call.name.clone(),
                    response: result,
                  }),
                  ..Default::default()
                });
              }
              Err( error ) =>
              {
                if self.config.logging_enabled
                {
                println!( "Function error : {}", error );
                }

                function_responses.push( Part
                {
                  text: None,
                  inline_data: None,
                  function_call: None,
                  function_response: Some( FunctionResponse
                  {
                    name: function_call.name.clone(),
                  response : json!({ "error": error.to_string() }),
                  }),
                  ..Default::default()
                });
              }
            }
          }
          else if let Some( text ) = &part.text
          {
            final_response = text.clone();
          }
        }

        // If there are function responses, add them to conversation and continue
        if has_function_calls
        {
          if !function_responses.is_empty()
          {
            self.conversation_history.push( Content
            {
              role: "user".to_string(),
              parts: function_responses,
            });
          }
        }
        else
        {
          // No function calls, task is complete
          break;
        }
      }
      else
      {
        return Err( "No response candidate received".into() );
      }
    }

    if iteration >= self.config.max_iterations
    {
      if self.config.logging_enabled
      {
        println!( "Maximum iterations reached" );
      }
    }

    if self.config.logging_enabled
    {
      println!( "\nExecution Summary:" );
    println!( "{}", serde_json::to_string_pretty( &self.tool_registry.get_execution_summary() )? );
    }

    Ok( final_response )
  }

  /// Run agent in interactive mode
  pub async fn run_interactive_mode( &mut self ) -> Result< (), Box< dyn std::error::Error > >
  {
    println!( "Interactive AI Agent Mode" );
  println!( "Available tools : {:?}", self.config.available_tools );
    println!( "Type 'exit' to quit, 'tools' to list available tools" );

    loop
    {
      println!( "\nEnter your task or question:" );
      
      let mut input = String::new();
      std ::io::stdin().read_line( &mut input )?;
      let input = input.trim();

      match input
      {
        "exit" => break,
        "tools" =>
        {
        println!( "Available tools : {:?}", self.config.available_tools );
          continue;
        }
        task if !task.is_empty() =>
        {
          match self.execute_task( task ).await
          {
          Ok( response ) => println!( "\nAgent : {}", response ),
          Err( error ) => println!( "Error : {}", error ),
          }
        }
        _ => continue,
      }
    }

    Ok( () )
  }

  /// Run agent in demo mode
  pub async fn run_demo_mode( &mut self, service: &str ) -> Result< (), Box< dyn std::error::Error > >
  {
    match service
    {
      "weather_api" =>
      {
        let demo_task = "Get the weather for Tokyo and New York, then compare them and tell me which city has better weather for outdoor activities today.";
        println!( "Weather API Integration Demo" );
      println!( "Task : {}", demo_task );
    
        let response = self.execute_task( demo_task ).await?;
      println!( "\nFinal Response:\n{}", response );
      }
      "multi_step" =>
      {
        let demo_task = "I want to plan a trip to Paris. Check the weather there, search for flights from New York for January 25th, and calculate what 15% tip would be on a $150 restaurant bill.";
        println!( "Multi-step Workflow Demo" );
      println!( "Task : {}", demo_task );
    
        let response = self.execute_task( demo_task ).await?;
      println!( "\nFinal Response:\n{}", response );
      }
      "data_analysis" =>
      {
        let demo_task = "Query the database for recent user analytics, then calculate the percentage increase if revenue grew by 15%, and search for information about industry benchmarks for conversion rates.";
        println!( "Data Analysis Demo" );
      println!( "Task : {}", demo_task );
    
        let response = self.execute_task( demo_task ).await?;
      println!( "\nFinal Response:\n{}", response );
      }
    _ => return Err( format!( "Unknown demo service : {}", service ).into() ),
    }

    Ok( () )
  }
}

fn parse_args() -> AgentConfig
{
  let args: Vec< String > = env::args().collect();
  let mut config = AgentConfig::default();

  let mut i = 1;
  while i < args.len()
  {
    match args[ i ].as_str()
    {
      "--agent-mode" =>
      {
        if i + 1 < args.len()
        {
          match args[ i + 1 ].as_str()
          {
            "interactive" => config.agent_mode = AgentMode::Interactive,
            "automated" => config.agent_mode = AgentMode::Automated,
            mode => config.agent_mode = AgentMode::Demo( mode.to_string() ),
          }
          i += 1;
        }
      }
      "--tools" =>
      {
        if i + 1 < args.len()
        {
          if args[ i + 1 ] == "all"
          {
            config.available_tools = vec![ "all".to_string() ];
          }
          else
          {
            config.available_tools = args[ i + 1 ]
            .split( ',' )
            .map( |s| s.trim().to_string() )
            .collect();
          }
          i += 1;
        }
      }
      "--task" =>
      {
        if i + 1 < args.len()
        {
          config.task_description = Some( args[ i + 1 ].clone() );
          config.agent_mode = AgentMode::Automated;
          i += 1;
        }
      }
      "--demo" =>
      {
        if i + 1 < args.len()
        {
          config.agent_mode = AgentMode::Demo( "demo".to_string() );
          i += 1;
        }
      }
      "--service" =>
      {
        if i + 1 < args.len()
        {
          config.demo_service = Some( args[ i + 1 ].clone() );
          i += 1;
        }
      }
      "--max-iterations" =>
      {
        if i + 1 < args.len()
        {
          if let Ok( max_iter ) = args[ i + 1 ].parse::< usize >()
          {
            config.max_iterations = max_iter;
          }
          i += 1;
        }
      }
      "--timeout" =>
      {
        if i + 1 < args.len()
        {
          if let Ok( timeout ) = args[ i + 1 ].parse::< u64 >()
          {
            config.timeout_seconds = timeout;
          }
          i += 1;
        }
      }
      "--quiet" =>
      {
        config.logging_enabled = false;
      }
    _ => {}
    }
    i += 1;
  }

  config
}

fn print_usage()
{
  println!( "Comprehensive Function Calling & Tool Integration Example" );
  println!();
  println!( "Usage:" );
  println!( "  cargo run --example gemini_function_calling [OPTIONS]" );
  println!();
  println!( "Options:" );
  println!( "  --agent-mode MODE     Set agent mode: interactive, automated" );
  println!( "  --tools TOOLS         Comma-separated list of tools or 'all'" );
  println!( "  --task TASK          Execute specific task (sets mode to automated)" );
  println!( "  --demo               Run demonstration mode" );
  println!( "  --service SERVICE    Demo service: weather_api, multi_step, data_analysis" );
  println!( "  --max-iterations N   Maximum workflow iterations (default: 10)" );
  println!( "  --timeout SECONDS    Function timeout in seconds (default: 30)" );
  println!( "  --quiet              Disable logging output" );
  println!();
  println!( "Available tools:" );
  println!( "  weather      - Get weather information for locations" );
  println!( "  calculator   - Perform mathematical calculations" );
  println!( "  web_search   - Search the web for information" );
  println!( "  search_flights - Find flight options between cities" );
  println!( "  query_database - Query simulated database for analytics" );
  println!();
  println!( "Examples:" );
  println!( "  # Interactive mode with specific tools" );
  println!( "  cargo run --example gemini_function_calling -- --agent-mode interactive --tools weather,calculator" );
  println!();
  println!( "  # Execute specific task with all tools" );
  println!( "  cargo run --example gemini_function_calling -- --task \"Plan a trip to Tokyo\" --tools all" );
  println!();
  println!( "  # Run weather API demo" );
  println!( "  cargo run --example gemini_function_calling -- --demo --service weather_api" );
}

#[ tokio::main ]
async fn main() -> Result< (), Box< dyn core::error::Error > >
{
  let config = parse_args();

  if env::args().any( |arg| arg == "--help" || arg == "-h" )
  {
    print_usage();
    return Ok( () );
  }

  let mut agent = FunctionCallingAgent::new( config.clone() )?;

  match config.agent_mode
  {
    AgentMode::Interactive =>
    {
      agent.run_interactive_mode().await?;
    }
    AgentMode::Automated =>
    {
      if let Some( task ) = &config.task_description
      {
        let response = agent.execute_task( task ).await?;
        if !config.logging_enabled
        {
        println!( "{response}" );
        }
      }
      else
      {
        println!( "No task specified for automated mode. Use --task \"your task here\"" );
        print_usage();
      }
    }
    AgentMode::Demo( _ ) =>
    {
      let service = config.demo_service.as_deref().unwrap_or( "weather_api" );
      agent.run_demo_mode( service ).await?;
    }
  }

  Ok( () )
}