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
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
use crate::GenaiError;
use crate::http::context::HttpContext;
use crate::wire::{LoudWirePrinter, WireInspector};
use reqwest::Client as ReqwestClient;
use std::sync::Arc;
use std::time::Duration;
/// Logs a request body at debug level, preferring JSON format when possible.
fn log_request_body<T: std::fmt::Debug + serde::Serialize>(body: &T) {
match serde_json::to_string_pretty(body) {
Ok(json) => tracing::debug!("Request Body (JSON):\n{json}"),
Err(_) => tracing::debug!("Request Body: {body:#?}"),
}
}
/// Logs a response body at debug level, preferring JSON format when possible.
fn log_response_body<T: std::fmt::Debug + serde::Serialize>(body: &T) {
match serde_json::to_string_pretty(body) {
Ok(json) => tracing::debug!("Response Body (JSON):\n{json}"),
Err(_) => tracing::debug!("Response Body: {body:#?}"),
}
}
/// The main client for interacting with the Google Generative AI API.
#[derive(Clone)]
pub struct Client {
/// Shared HTTP context: reqwest client, API key, wire inspectors, and
/// the request-id counter for wire-event correlation.
pub(crate) http: HttpContext,
}
// Custom Debug implementation that redacts the API key for security.
// This prevents accidental exposure of credentials in logs, error messages, or debug output.
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("api_key", &"[REDACTED]")
.field("http_client", &self.http.http_client)
.finish()
}
}
/// Appends a [`LoudWirePrinter`] when the `LOUD_WIRE` environment variable is
/// set. Checked once at `Client` construction time.
fn with_env_inspectors(mut inspectors: Vec<Arc<dyn WireInspector>>) -> Vec<Arc<dyn WireInspector>> {
if std::env::var("LOUD_WIRE").is_ok() {
inspectors.push(Arc::new(LoudWirePrinter::new()));
}
inspectors
}
/// Builder for `Client` instances.
///
/// # Example
///
/// ```
/// use genai_rs::Client;
/// use std::time::Duration;
///
/// let client = Client::builder("api_key".to_string())
/// .with_timeout(Duration::from_secs(120))
/// .with_connect_timeout(Duration::from_secs(10))
/// .build()?;
/// # Ok::<(), genai_rs::GenaiError>(())
/// ```
pub struct ClientBuilder {
api_key: String,
timeout: Option<Duration>,
connect_timeout: Option<Duration>,
wire_inspectors: Vec<Arc<dyn WireInspector>>,
}
// Custom Debug implementation that redacts the API key for security.
impl std::fmt::Debug for ClientBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClientBuilder")
.field("api_key", &"[REDACTED]")
.field("timeout", &self.timeout)
.field("connect_timeout", &self.connect_timeout)
.field("wire_inspectors", &self.wire_inspectors.len())
.finish()
}
}
impl ClientBuilder {
/// Sets the total request timeout.
///
/// This is the maximum time a request can take from start to finish,
/// including connection time, sending the request, and receiving the response.
///
/// For LLM requests that may take a long time to generate responses,
/// consider setting a longer timeout (e.g., 120-300 seconds).
///
/// If not set, requests will wait indefinitely (no timeout).
/// Connection-level timeouts like TCP keepalive may still apply at the OS level.
///
/// # Example
///
/// ```
/// use genai_rs::Client;
/// use std::time::Duration;
///
/// let client = Client::builder("api_key".to_string())
/// .with_timeout(Duration::from_secs(120))
/// .build()?;
/// # Ok::<(), genai_rs::GenaiError>(())
/// ```
#[must_use]
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
/// Sets the connection timeout.
///
/// This is the maximum time to wait for establishing a connection to the server.
/// A shorter timeout here can help fail fast if the network is unavailable.
///
/// If not set, the connection phase will wait indefinitely (no timeout).
///
/// # Example
///
/// ```
/// use genai_rs::Client;
/// use std::time::Duration;
///
/// let client = Client::builder("api_key".to_string())
/// .with_connect_timeout(Duration::from_secs(10))
/// .build()?;
/// # Ok::<(), genai_rs::GenaiError>(())
/// ```
#[must_use]
pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = Some(timeout);
self
}
/// Adds a wire inspector that observes raw API traffic.
///
/// Inspectors receive a [`crate::wire::WireEvent`] for every request,
/// response, error body, SSE frame, and file upload. Multiple inspectors
/// may be registered; each receives every event. When the `LOUD_WIRE`
/// environment variable is set, a [`crate::wire::LoudWirePrinter`] is
/// appended automatically at `build()` time.
///
/// # Example
///
/// ```
/// use genai_rs::Client;
/// use genai_rs::wire::TracingForwarder;
/// use std::sync::Arc;
///
/// let client = Client::builder("api_key".to_string())
/// .add_wire_inspector(Arc::new(TracingForwarder::new()))
/// .build()?;
/// # Ok::<(), genai_rs::GenaiError>(())
/// ```
#[must_use]
pub fn add_wire_inspector(mut self, inspector: Arc<dyn WireInspector>) -> Self {
self.wire_inspectors.push(inspector);
self
}
/// Builds the `Client`.
///
/// # Errors
///
/// Returns an error if the underlying HTTP client cannot be constructed. This should only
/// happen in exceptional circumstances such as TLS backend initialization failures.
pub fn build(self) -> Result<Client, GenaiError> {
let mut builder = ReqwestClient::builder();
if let Some(timeout) = self.timeout {
builder = builder.timeout(timeout);
}
if let Some(connect_timeout) = self.connect_timeout {
builder = builder.connect_timeout(connect_timeout);
}
let http_client = builder
.build()
.map_err(|e| GenaiError::ClientBuild(e.to_string()))?;
Ok(Client {
http: HttpContext::new(
http_client,
self.api_key,
with_env_inspectors(self.wire_inspectors),
),
})
}
}
impl Client {
/// Creates a new builder for `Client` instances.
///
/// # Arguments
///
/// * `api_key` - Your Google AI API key.
#[must_use]
pub const fn builder(api_key: String) -> ClientBuilder {
ClientBuilder {
api_key,
timeout: None,
connect_timeout: None,
wire_inspectors: Vec::new(),
}
}
/// Creates a new `GenAI` client.
///
/// # Arguments
///
/// * `api_key` - Your Google AI API key.
#[must_use]
pub fn new(api_key: String) -> Self {
Self {
http: HttpContext::new(
ReqwestClient::new(),
api_key,
with_env_inspectors(Vec::new()),
),
}
}
// --- Interactions API methods ---
/// Creates a builder for constructing an interaction request.
///
/// This provides a fluent interface for building interactions with models or agents.
/// Use this method for a more ergonomic API compared to manually constructing
/// `InteractionRequest`.
///
/// # Examples
///
/// ```no_run
/// # use genai_rs::Client;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::builder("api_key".to_string()).build()?;
///
/// // Simple interaction
/// let response = client.interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_text("Hello, world!")
/// .create()
/// .await?;
///
/// // Stateful conversation (requires stored interaction)
/// let response2 = client.interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_text("What did I just say?")
/// .with_previous_interaction(response.id.as_ref().expect("stored interaction has id"))
/// .create()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn interaction(&self) -> crate::request_builder::InteractionBuilder<'_> {
crate::request_builder::InteractionBuilder::new(self)
}
/// Creates a new interaction using the Gemini Interactions API.
///
/// The Interactions API provides a unified interface for working with models and agents,
/// with built-in support for stateful conversations, function calling, and long-running tasks.
///
/// # Arguments
///
/// * `request` - The interaction request with model/agent, input, and optional configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The HTTP request fails
/// - Response parsing fails
/// - The API returns an error
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("your-api-key".to_string());
///
/// // Build a reusable request with the builder, then execute it.
/// let request = client
/// .interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_text("Hello, world!")
/// .build()?;
///
/// let response = client.execute(request).await?;
/// println!("Interaction ID: {:?}", response.id);
/// # Ok(())
/// # }
/// ```
///
/// # Streaming Example
///
/// ```no_run
/// use genai_rs::{Client, StreamChunk};
/// use futures_util::StreamExt;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::builder("api_key".to_string()).build()?;
/// let mut request = client
/// .interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_text("Count to 5")
/// .build()?;
/// request.stream = Some(true);
///
/// let mut last_event_id = None;
/// let mut stream = client.execute_stream(request);
/// while let Some(result) = stream.next().await {
/// let event = result?;
/// last_event_id = event.event_id.clone(); // Track for resume
/// match event.chunk {
/// StreamChunk::StepDelta { delta, .. } => {
/// if let Some(text) = delta.as_text() {
/// print!("{}", text);
/// }
/// }
/// StreamChunk::Completed(response) => {
/// println!("\nDone! ID: {:?}", response.id);
/// }
/// _ => {} // Handle unknown future variants
/// }
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Retry Example
///
/// ```no_run
/// use genai_rs::Client;
/// use std::time::Duration;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api_key".to_string());
/// let request = client.interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_text("Hello!")
/// .build()?;
///
/// // Retry loop with exponential backoff
/// let mut attempts = 0;
/// let response = loop {
/// match client.execute(request.clone()).await {
/// Ok(r) => break r,
/// Err(e) if e.is_retryable() && attempts < 3 => {
/// attempts += 1;
/// tokio::time::sleep(Duration::from_millis(100 * 2u64.pow(attempts))).await;
/// }
/// Err(e) => return Err(e.into()),
/// }
/// };
/// # Ok(())
/// # }
/// ```
#[tracing::instrument(skip(self), fields(model = ?request.model, agent = ?request.agent))]
pub async fn execute(
&self,
request: crate::InteractionRequest,
) -> Result<crate::InteractionResponse, GenaiError> {
tracing::debug!("Creating interaction");
log_request_body(&request);
let response = crate::http::interactions::create_interaction(&self.http, request).await?;
log_response_body(&response);
tracing::debug!("Interaction created: ID={:?}", response.id);
Ok(response)
}
/// Executes a pre-built interaction request with streaming.
///
/// This is the streaming variant of [`execute()`](Self::execute).
///
/// Returns a stream of [`StreamEvent`](crate::StreamEvent) items as they arrive.
/// Each event contains:
/// - `chunk`: The content (delta or complete response)
/// - `event_id`: Optional ID for resuming interrupted streams
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Client, StreamChunk};
/// use futures_util::StreamExt;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api_key".to_string());
///
/// let request = client.interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_text("Count to 5")
/// .build()?;
///
/// let mut stream = client.execute_stream(request);
/// while let Some(result) = stream.next().await {
/// let event = result?;
/// match event.chunk {
/// StreamChunk::StepDelta { delta, .. } => {
/// if let Some(text) = delta.as_text() {
/// print!("{}", text);
/// }
/// }
/// StreamChunk::Completed(response) => {
/// println!("\nDone!");
/// }
/// _ => {}
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[tracing::instrument(skip(self), fields(model = ?request.model, agent = ?request.agent))]
pub fn execute_stream(
&self,
request: crate::InteractionRequest,
) -> futures_util::stream::BoxStream<'_, Result<crate::StreamEvent, GenaiError>> {
use futures_util::StreamExt;
tracing::debug!("Creating streaming interaction");
log_request_body(&request);
let stream = crate::http::interactions::create_interaction_stream(&self.http, request);
stream
.map(move |result| {
result.inspect(|event| {
tracing::debug!(
"Received stream event: chunk={:?}, event_id={:?}",
event.chunk,
event.event_id
);
})
})
.boxed()
}
/// Retrieves an existing interaction by its ID.
///
/// Useful for checking the status of long-running interactions or agents,
/// or for retrieving the full conversation history.
///
/// # Arguments
///
/// * `interaction_id` - The unique identifier of the interaction to retrieve.
///
/// # Errors
///
/// Returns an error if:
/// - The HTTP request fails
/// - Response parsing fails
/// - The API returns an error
pub async fn get_interaction(
&self,
interaction_id: &str,
) -> Result<crate::InteractionResponse, GenaiError> {
tracing::debug!("Getting interaction: ID={interaction_id}");
let response =
crate::http::interactions::get_interaction(&self.http, interaction_id, false).await?;
log_response_body(&response);
tracing::debug!("Retrieved interaction: status={:?}", response.status);
Ok(response)
}
/// Retrieves an existing interaction by its ID, including the original input.
///
/// Like [`get_interaction()`](Self::get_interaction), but sets the
/// `include_input=true` query parameter so the response's `input` field is
/// populated.
///
/// Live behavior note (2026-07): the parameter is accepted, but the
/// Gemini API was observed to return identical responses with and
/// without it — no `input` echo (and no `generation_config` echo) was
/// observed on completed interactions.
///
/// # Errors
///
/// Returns an error if:
/// - The HTTP request fails
/// - Response parsing fails
/// - The API returns an error
pub async fn get_interaction_with_input(
&self,
interaction_id: &str,
) -> Result<crate::InteractionResponse, GenaiError> {
tracing::debug!("Getting interaction (with input): ID={interaction_id}");
let response =
crate::http::interactions::get_interaction(&self.http, interaction_id, true).await?;
log_response_body(&response);
tracing::debug!("Retrieved interaction: status={:?}", response.status);
Ok(response)
}
/// Retrieves an existing interaction by its ID with streaming.
///
/// Returns a stream of events for the interaction. This is useful for:
/// - Resuming an interrupted stream using `last_event_id`
/// - Streaming a long-running interaction's progress (e.g., deep research)
///
/// Each event includes an `event_id` that can be used to resume the stream
/// from that point if the connection is interrupted.
///
/// # Arguments
///
/// * `interaction_id` - The unique identifier of the interaction to stream.
/// * `last_event_id` - Optional event ID to resume from. Pass the last received
/// event's `event_id` to continue from where you left off.
///
/// # Returns
/// A boxed stream that yields `StreamEvent` items.
///
/// # Example
/// ```no_run
/// use genai_rs::{Client, StreamChunk};
/// use futures_util::StreamExt;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::builder("api_key".to_string()).build()?;
/// let interaction_id = "some-interaction-id";
///
/// // Resume a stream from a previous event
/// let last_event_id = Some("evt_abc123");
/// let mut stream = client.get_interaction_stream(interaction_id, last_event_id);
///
/// while let Some(result) = stream.next().await {
/// let event = result?;
/// println!("Event ID: {:?}", event.event_id);
/// match event.chunk {
/// StreamChunk::StepDelta { delta, .. } => {
/// if let Some(text) = delta.as_text() {
/// print!("{}", text);
/// }
/// }
/// StreamChunk::Completed(response) => {
/// println!("\nDone! Status: {:?}", response.status);
/// }
/// _ => {}
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_interaction_stream<'a>(
&'a self,
interaction_id: &'a str,
last_event_id: Option<&'a str>,
) -> futures_util::stream::BoxStream<'a, Result<crate::StreamEvent, GenaiError>> {
use futures_util::StreamExt;
tracing::debug!(
"Getting interaction stream: ID={}, resume_from={:?}",
interaction_id,
last_event_id
);
let stream = crate::http::interactions::get_interaction_stream(
&self.http,
interaction_id,
last_event_id,
);
stream
.map(move |result| {
result.inspect(|event| {
tracing::debug!(
"Received stream event: chunk={:?}, event_id={:?}",
event.chunk,
event.event_id
);
})
})
.boxed()
}
/// Deletes an interaction by its ID.
///
/// Removes the interaction from the server, freeing up storage and making it
/// unavailable for future reference via `previous_interaction_id`.
///
/// # Arguments
///
/// * `interaction_id` - The unique identifier of the interaction to delete.
///
/// # Errors
///
/// Returns an error if:
/// - The HTTP request fails
/// - The API returns an error
pub async fn delete_interaction(&self, interaction_id: &str) -> Result<(), GenaiError> {
tracing::debug!("Deleting interaction: ID={interaction_id}");
crate::http::interactions::delete_interaction(&self.http, interaction_id).await?;
tracing::debug!("Interaction deleted successfully");
Ok(())
}
/// Cancels an in-progress background interaction.
///
/// Only applicable to interactions created with `background: true` that are
/// still in `InProgress` status. Returns the updated interaction with
/// status `Cancelled`.
///
/// This is useful for:
/// - Halting long-running agent tasks (e.g., deep-research) when requirements change
/// - Cost control by stopping interactions consuming significant tokens
/// - Implementing timeout handling in application logic
/// - Supporting user-initiated cancellation in UIs
///
/// # Arguments
///
/// * `interaction_id` - The unique identifier of the interaction to cancel.
///
/// # Errors
///
/// Returns an error if:
/// - The interaction doesn't exist
/// - The interaction is not in a cancellable state (not background or already complete)
/// - The HTTP request fails
/// - The API returns an error
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Client, InteractionStatus};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("your-api-key".to_string());
///
/// // Start a background agent interaction
/// let response = client.interaction()
/// .with_agent("deep-research-pro-preview-12-2025")
/// .with_text("Research AI safety")
/// .with_background(true)
/// .with_store_enabled()
/// .create()
/// .await?;
///
/// let interaction_id = response.id.as_ref().expect("stored interaction has id");
///
/// // Later, cancel if still in progress
/// if response.status == InteractionStatus::InProgress {
/// let cancelled = client.cancel_interaction(interaction_id).await?;
/// assert_eq!(cancelled.status, InteractionStatus::Cancelled);
/// println!("Interaction cancelled");
/// }
/// # Ok(())
/// # }
/// ```
pub async fn cancel_interaction(
&self,
interaction_id: &str,
) -> Result<crate::InteractionResponse, GenaiError> {
tracing::debug!("Cancelling interaction: ID={interaction_id}");
let response =
crate::http::interactions::cancel_interaction(&self.http, interaction_id).await?;
log_response_body(&response);
tracing::debug!("Interaction cancelled: status={:?}", response.status);
Ok(response)
}
// --- Webhooks resource methods (`/v1beta/webhooks`) ---
/// Registers a new webhook.
///
/// The returned webhook includes `new_signing_secret` — only populated on
/// create — which is used to verify event payload signatures. Store it
/// securely; it is not returned again.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error,
/// or response parsing fails.
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Client, Webhook, WebhookEvent};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let webhook = client.create_webhook(
/// &Webhook::new(
/// "https://example.com/hooks/genai",
/// vec![WebhookEvent::InteractionCompleted, WebhookEvent::InteractionFailed],
/// )
/// .with_name("my-hook"),
/// ).await?;
///
/// println!("Created {:?}; secret: {:?}", webhook.id, webhook.new_signing_secret);
/// # Ok(())
/// # }
/// ```
pub async fn create_webhook(
&self,
webhook: &crate::Webhook,
) -> Result<crate::Webhook, GenaiError> {
crate::http::webhooks::create_webhook(&self.http, webhook).await
}
/// Retrieves a registered webhook by ID.
///
/// # Errors
///
/// Returns an error if the webhook doesn't exist, the HTTP request fails,
/// or response parsing fails.
pub async fn get_webhook(&self, webhook_id: &str) -> Result<crate::Webhook, GenaiError> {
crate::http::webhooks::get_webhook(&self.http, webhook_id).await
}
/// Lists registered webhooks.
///
/// # Arguments
///
/// * `page_size` - Optional maximum number of webhooks per page.
/// * `page_token` - Optional token from a previous list call.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or response parsing fails.
pub async fn list_webhooks(
&self,
page_size: Option<u32>,
page_token: Option<&str>,
) -> Result<crate::WebhookListResponse, GenaiError> {
crate::http::webhooks::list_webhooks(&self.http, page_size, page_token).await
}
/// Updates a registered webhook.
///
/// # Arguments
///
/// * `webhook_id` - The webhook to update.
/// * `update` - The fields to change (only set fields are sent).
/// * `update_mask` - Optional comma-separated list of fields to update
/// (e.g. `"uri,subscribed_events"`).
///
/// Live behavior note (2026-07): `update_mask` is not required — PATCH
/// applies exactly the fields present in the body. The mask was also
/// observed to be ignored when supplied (fields outside the mask still
/// updated), so rely on the partial body, not the mask, to scope updates.
///
/// # Errors
///
/// Returns an error if the webhook doesn't exist, the HTTP request fails,
/// or response parsing fails.
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Client, WebhookState, WebhookUpdate};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("api-key".to_string());
/// // Temporarily disable a webhook
/// let updated = client.update_webhook(
/// "wh-123",
/// &WebhookUpdate::new().with_state(WebhookState::Disabled),
/// Some("state"),
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn update_webhook(
&self,
webhook_id: &str,
update: &crate::WebhookUpdate,
update_mask: Option<&str>,
) -> Result<crate::Webhook, GenaiError> {
crate::http::webhooks::update_webhook(&self.http, webhook_id, update, update_mask).await
}
/// Deletes a registered webhook.
///
/// # Errors
///
/// Returns an error if the webhook doesn't exist or the HTTP request fails.
pub async fn delete_webhook(&self, webhook_id: &str) -> Result<(), GenaiError> {
crate::http::webhooks::delete_webhook(&self.http, webhook_id).await
}
/// Sends a test event to a webhook (`:ping`).
///
/// Use this to verify your endpoint receives and validates deliveries
/// before relying on it for real events.
///
/// Live behavior note (2026-07): the RPC accepts an empty JSON body
/// (`{}`, which this client sends) and returns `{}` on success even
/// when the destination URI is unreachable.
///
/// # Errors
///
/// Returns an error if the webhook doesn't exist or the HTTP request fails.
pub async fn ping_webhook(&self, webhook_id: &str) -> Result<(), GenaiError> {
crate::http::webhooks::ping_webhook(&self.http, webhook_id).await
}
/// Rotates a webhook's signing secret (`:rotateSigningSecret`).
///
/// Returns the newly generated secret. Pass a
/// [`RevocationBehavior`](crate::RevocationBehavior) to control whether
/// previous secrets stay valid for 24 hours (safe rollover) or are
/// revoked immediately; `None` uses the API default.
///
/// # Errors
///
/// Returns an error if the webhook doesn't exist, the HTTP request fails,
/// or response parsing fails.
pub async fn rotate_webhook_signing_secret(
&self,
webhook_id: &str,
revocation_behavior: Option<crate::RevocationBehavior>,
) -> Result<crate::RotateSigningSecretResponse, GenaiError> {
crate::http::webhooks::rotate_signing_secret(&self.http, webhook_id, revocation_behavior)
.await
}
// --- Agents resource methods (`/v1beta/agents`) ---
/// Creates a custom agent.
///
/// Once created, run the agent with
/// [`InteractionBuilder::with_agent()`](crate::InteractionBuilder::with_agent)
/// using its ID.
///
/// Live behavior notes (2026-07):
/// - Agent creation was rejected with a generic
/// `400 "Request contains an invalid argument."` for every payload
/// tried on a standard Gemini API key (even schema-valid ones), which
/// suggests the resource is allowlisted/gated. Field names are still
/// validated first (snake_case: `id`, `base_agent`,
/// `system_instruction`, `description`, `tools`, `base_environment`).
/// - `tools` on an agent only accepts `code_execution`, `google_search`,
/// and `url_context` (per the API's own validation error).
/// - Managed agent IDs (e.g. `deep-research-preview-04-2026`) are not
/// retrievable through `GET /v1beta/agents/{id}` (404).
///
/// # Errors
///
/// Returns an error if the HTTP request fails, the API returns an error,
/// or response parsing fails.
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Agent, Client, Tool};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let agent = client.create_agent(
/// &Agent::new("customer-sentinel")
/// .with_system_instruction("You monitor customer feedback.")
/// .add_tool(Tool::CodeExecution),
/// ).await?;
///
/// // Run it
/// let response = client.interaction()
/// .with_agent(agent.id.as_deref().unwrap_or("customer-sentinel"))
/// .with_text("Summarize this week's feedback")
/// .create()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_agent(&self, agent: &crate::Agent) -> Result<crate::Agent, GenaiError> {
crate::http::agents::create_agent(&self.http, agent).await
}
/// Retrieves an agent by ID.
///
/// # Errors
///
/// Returns an error if the agent doesn't exist, the HTTP request fails,
/// or response parsing fails.
pub async fn get_agent(&self, agent_id: &str) -> Result<crate::Agent, GenaiError> {
crate::http::agents::get_agent(&self.http, agent_id).await
}
/// Lists agents.
///
/// # Arguments
///
/// * `page_size` - Optional maximum number of agents per page.
/// * `page_token` - Optional token from a previous list call.
/// * `parent` - Optional parent resource filter.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or response parsing fails.
pub async fn list_agents(
&self,
page_size: Option<u32>,
page_token: Option<&str>,
parent: Option<&str>,
) -> Result<crate::AgentListResponse, GenaiError> {
crate::http::agents::list_agents(&self.http, page_size, page_token, parent).await
}
/// Deletes an agent by ID.
///
/// # Errors
///
/// Returns an error if the agent doesn't exist or the HTTP request fails.
pub async fn delete_agent(&self, agent_id: &str) -> Result<(), GenaiError> {
crate::http::agents::delete_agent(&self.http, agent_id).await
}
// --- Files API methods ---
/// Uploads a file from a path to the Files API.
///
/// Files are stored for 48 hours and can be referenced in interactions by their URI.
/// This is more efficient than inline base64 encoding for large files or files
/// that will be used across multiple interactions.
///
/// # Arguments
///
/// * `path` - Path to the file to upload
///
/// # Errors
///
/// Returns an error if:
/// - The file cannot be read
/// - The MIME type cannot be determined
/// - The upload fails
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Client, Content};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// // Upload a video file
/// let file = client.upload_file("video.mp4").await?;
/// println!("Uploaded: {} -> {}", file.name, file.uri);
///
/// // Use in interaction
/// let response = client.interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_content(vec![
/// Content::text("Describe this video"),
/// Content::from_file(&file),
/// ])
/// .create()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn upload_file(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<crate::FileMetadata, GenaiError> {
let path = path.as_ref();
// Read file contents
let file_data = tokio::fs::read(path).await.map_err(|e| {
tracing::warn!("Failed to read file '{}': {}", path.display(), e);
GenaiError::InvalidInput(format!("Failed to read file '{}': {}", path.display(), e))
})?;
// Detect MIME type from extension
let mime_type = crate::multimodal::detect_mime_type(path).ok_or_else(|| {
tracing::warn!(
"Could not determine MIME type for '{}' - unknown extension",
path.display()
);
GenaiError::InvalidInput(format!(
"Could not determine MIME type for '{}'. Please use upload_file_with_mime() to specify explicitly.",
path.display()
))
})?;
// Use filename as display name
let display_name = path
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.to_string());
tracing::debug!(
"Uploading file: path={}, size={} bytes, mime_type={}",
path.display(),
file_data.len(),
mime_type
);
crate::http::files::upload_file(&self.http, file_data, mime_type, display_name.as_deref())
.await
}
/// Uploads a file with an explicit MIME type.
///
/// Use this when automatic MIME type detection isn't suitable.
///
/// # Arguments
///
/// * `path` - Path to the file to upload
/// * `mime_type` - MIME type of the file (e.g., "video/mp4")
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let file = client.upload_file_with_mime("data.bin", "application/octet-stream").await?;
/// # Ok(())
/// # }
/// ```
pub async fn upload_file_with_mime(
&self,
path: impl AsRef<std::path::Path>,
mime_type: &str,
) -> Result<crate::FileMetadata, GenaiError> {
let path = path.as_ref();
let file_data = tokio::fs::read(path).await.map_err(|e| {
tracing::warn!("Failed to read file '{}': {}", path.display(), e);
GenaiError::InvalidInput(format!("Failed to read file '{}': {}", path.display(), e))
})?;
let display_name = path
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.to_string());
tracing::debug!(
"Uploading file: path={}, size={} bytes, mime_type={}",
path.display(),
file_data.len(),
mime_type
);
crate::http::files::upload_file(&self.http, file_data, mime_type, display_name.as_deref())
.await
}
/// Uploads file bytes directly with a specified MIME type.
///
/// Use this when you already have file contents in memory.
///
/// # Arguments
///
/// * `data` - File contents as bytes
/// * `mime_type` - MIME type of the file
/// * `display_name` - Optional display name for the file
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// // Upload bytes from memory
/// let video_bytes = std::fs::read("video.mp4")?;
/// let file = client.upload_file_bytes(video_bytes, "video/mp4", Some("my-video")).await?;
/// # Ok(())
/// # }
/// ```
pub async fn upload_file_bytes(
&self,
data: Vec<u8>,
mime_type: &str,
display_name: Option<&str>,
) -> Result<crate::FileMetadata, GenaiError> {
tracing::debug!(
"Uploading file bytes: size={} bytes, mime_type={}, display_name={:?}",
data.len(),
mime_type,
display_name
);
crate::http::files::upload_file(&self.http, data, mime_type, display_name).await
}
/// Gets metadata for an uploaded file.
///
/// Use this to check the processing status of a recently uploaded file.
///
/// # Arguments
///
/// * `file_name` - The resource name of the file (e.g., "files/abc123")
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let file = client.get_file("files/abc123").await?;
/// if file.is_active() {
/// println!("File is ready to use");
/// } else if file.is_processing() {
/// println!("File is still processing...");
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_file(&self, file_name: &str) -> Result<crate::FileMetadata, GenaiError> {
crate::http::files::get_file(&self.http, file_name).await
}
/// Lists all uploaded files.
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let response = client.list_files(None, None).await?;
/// for file in response.files {
/// println!("{}: {} ({})", file.name, file.display_name.as_deref().unwrap_or(""), file.mime_type);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn list_files(
&self,
page_size: Option<u32>,
page_token: Option<&str>,
) -> Result<crate::ListFilesResponse, GenaiError> {
crate::http::files::list_files(&self.http, page_size, page_token).await
}
/// Deletes an uploaded file.
///
/// # Arguments
///
/// * `file_name` - The resource name of the file to delete (e.g., "files/abc123")
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// // Upload, use, then delete
/// let file = client.upload_file("video.mp4").await?;
/// // ... use in interactions ...
/// client.delete_file(&file.name).await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_file(&self, file_name: &str) -> Result<(), GenaiError> {
crate::http::files::delete_file(&self.http, file_name).await
}
/// Uploads a file using chunked transfer to minimize memory usage.
///
/// Unlike `upload_file`, this method streams the file from disk in chunks,
/// never loading the entire file into memory. This is ideal for large files
/// (500MB-2GB) or memory-constrained environments.
///
/// # Arguments
///
/// * `path` - Path to the file to upload
///
/// # Returns
///
/// Returns a tuple of:
/// - `FileMetadata`: The uploaded file's metadata
/// - `ResumableUpload`: A handle that can be used to resume if the upload is interrupted
///
/// # Memory Usage
///
/// This method uses approximately 8MB of memory for buffering, regardless of
/// the file size. A 2GB file uses the same memory as a 10MB file.
///
/// # Errors
///
/// Returns an error if:
/// - The file cannot be read
/// - The MIME type cannot be determined
/// - The upload fails
///
/// # Example
///
/// ```no_run
/// use genai_rs::{Client, Content};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// // Upload a large video file without loading it all into memory
/// let (file, _upload_handle) = client.upload_file_chunked("large_video.mp4").await?;
/// println!("Uploaded: {} -> {}", file.name, file.uri);
///
/// // Use in interaction
/// let response = client.interaction()
/// .with_model("gemini-3-flash-preview")
/// .with_content(vec![
/// Content::text("Describe this video"),
/// Content::from_file(&file),
/// ])
/// .create()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn upload_file_chunked(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<(crate::FileMetadata, crate::ResumableUpload), GenaiError> {
let path = path.as_ref();
// Detect MIME type from extension
let mime_type = crate::multimodal::detect_mime_type(path).ok_or_else(|| {
tracing::warn!(
"Could not determine MIME type for '{}' - unknown extension",
path.display()
);
GenaiError::InvalidInput(format!(
"Could not determine MIME type for '{}'. Please use upload_file_chunked_with_mime() to specify explicitly.",
path.display()
))
})?;
// Use filename as display name
let display_name = path
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.to_string());
tracing::debug!(
"Chunked upload: path={}, mime_type={}",
path.display(),
mime_type
);
crate::http::files::upload_file_chunked(
&self.http,
path,
mime_type,
display_name.as_deref(),
)
.await
}
/// Uploads a file using chunked transfer with an explicit MIME type.
///
/// Use this when automatic MIME type detection isn't suitable.
///
/// # Arguments
///
/// * `path` - Path to the file to upload
/// * `mime_type` - MIME type of the file (e.g., "video/mp4")
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let (file, _) = client.upload_file_chunked_with_mime(
/// "data.bin",
/// "application/octet-stream"
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn upload_file_chunked_with_mime(
&self,
path: impl AsRef<std::path::Path>,
mime_type: &str,
) -> Result<(crate::FileMetadata, crate::ResumableUpload), GenaiError> {
let path = path.as_ref();
let display_name = path
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.to_string());
tracing::debug!(
"Chunked upload: path={}, mime_type={}",
path.display(),
mime_type
);
crate::http::files::upload_file_chunked(
&self.http,
path,
mime_type,
display_name.as_deref(),
)
.await
}
/// Uploads a file using chunked transfer with a custom chunk size.
///
/// This is the same as `upload_file_chunked_with_mime` but allows
/// specifying the chunk size for streaming. Larger chunks are more
/// efficient for fast networks, while smaller chunks use less memory.
///
/// # Arguments
///
/// * `path` - Path to the file to upload
/// * `mime_type` - MIME type of the file
/// * `chunk_size` - Size of chunks to stream in bytes (default: 8MB)
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// // Use 16MB chunks for faster upload on a fast network
/// let chunk_size = 16 * 1024 * 1024;
/// let (file, _) = client.upload_file_chunked_with_options(
/// "large_video.mp4",
/// "video/mp4",
/// chunk_size
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn upload_file_chunked_with_options(
&self,
path: impl AsRef<std::path::Path>,
mime_type: &str,
chunk_size: usize,
) -> Result<(crate::FileMetadata, crate::ResumableUpload), GenaiError> {
let path = path.as_ref();
let display_name = path
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.to_string());
tracing::debug!(
"Chunked upload: path={}, mime_type={}, chunk_size={}",
path.display(),
mime_type,
chunk_size
);
crate::http::files::upload_file_chunked_with_chunk_size(
&self.http,
path,
mime_type,
display_name.as_deref(),
chunk_size,
)
.await
}
/// Waits for a file to finish processing.
///
/// Some files (especially videos) require processing before they can be used.
/// This method polls the file status until it becomes active or fails.
///
/// # Arguments
///
/// * `file` - The file metadata to wait for
/// * `poll_interval` - How often to check the status
/// * `timeout` - Maximum time to wait
///
/// # Returns
///
/// Returns the updated file metadata when processing completes.
///
/// # Errors
///
/// Returns an error if:
/// - The file processing fails
/// - The timeout is exceeded
///
/// # Example
///
/// ```no_run
/// use genai_rs::Client;
/// use std::time::Duration;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("api-key".to_string());
///
/// let file = client.upload_file("large_video.mp4").await?;
///
/// // Wait for processing to complete
/// let ready_file = client.wait_for_file_ready(
/// &file,
/// Duration::from_secs(2),
/// Duration::from_secs(120)
/// ).await?;
///
/// println!("File ready: {}", ready_file.uri);
/// # Ok(())
/// # }
/// ```
pub async fn wait_for_file_ready(
&self,
file: &crate::FileMetadata,
poll_interval: std::time::Duration,
timeout: std::time::Duration,
) -> Result<crate::FileMetadata, GenaiError> {
use std::time::Instant;
let start = Instant::now();
loop {
let current = self.get_file(&file.name).await?;
if current.is_active() {
return Ok(current);
}
if current.is_failed() {
let error_code = current.error.as_ref().and_then(|e| e.code);
let error_msg = current
.error
.as_ref()
.and_then(|e| e.message.as_deref())
.unwrap_or("File processing failed without details");
tracing::error!(
"File '{}' processing failed: code={:?}, message={}",
file.name,
error_code,
error_msg
);
// Use Api error since this is a server-side processing failure
return Err(GenaiError::Api {
status_code: error_code.map_or(500, |c| c as u16),
message: format!("File processing failed: {}", error_msg),
request_id: None,
retry_after: None,
});
}
// Log unknown states per Evergreen logging strategy
if let Some(state) = ¤t.state
&& state.is_unknown()
{
tracing::warn!(
"File '{}' is in unknown state {:?}, continuing to poll. \
This may indicate API evolution - consider updating genai-rs.",
file.name,
state
);
}
if start.elapsed() > timeout {
// Use Internal error since this is an operational issue, not invalid input
let state_info = current
.state
.as_ref()
.map(|s| format!("{:?}", s))
.unwrap_or_else(|| "unknown".to_string());
return Err(GenaiError::Internal(format!(
"Timeout waiting for file '{}' to be ready (waited {:?}, last state: {}). \
The file may still be processing - try again with a longer timeout.",
file.name,
start.elapsed(),
state_info
)));
}
tracing::debug!(
"File '{}' still processing, waiting {:?}...",
file.name,
poll_interval
);
tokio::time::sleep(poll_interval).await;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_client_builder_default() {
let client = Client::builder("test_key".to_string()).build().unwrap();
assert_eq!(client.http.api_key, "test_key");
}
#[test]
fn test_client_builder_with_timeout() {
let client = Client::builder("test_key".to_string())
.with_timeout(Duration::from_secs(120))
.build()
.unwrap();
assert_eq!(client.http.api_key, "test_key");
// Note: We can't easily inspect the reqwest client's timeout,
// but this test verifies the builder chain works
}
#[test]
fn test_client_builder_with_connect_timeout() {
let client = Client::builder("test_key".to_string())
.with_connect_timeout(Duration::from_secs(10))
.build()
.unwrap();
assert_eq!(client.http.api_key, "test_key");
}
#[test]
fn test_client_builder_with_both_timeouts() {
let client = Client::builder("test_key".to_string())
.with_timeout(Duration::from_secs(120))
.with_connect_timeout(Duration::from_secs(10))
.build()
.unwrap();
assert_eq!(client.http.api_key, "test_key");
}
#[test]
fn test_client_new() {
let client = Client::new("test_key".to_string());
assert_eq!(client.http.api_key, "test_key");
}
#[test]
fn test_client_debug_redacts_api_key() {
let client = Client::new("super_secret_api_key_12345".to_string());
let debug_output = format!("{:?}", client);
// API key should NOT appear in debug output
assert!(
!debug_output.contains("super_secret_api_key_12345"),
"API key was exposed in debug output: {}",
debug_output
);
// Should show [REDACTED] instead
assert!(
debug_output.contains("[REDACTED]"),
"Debug output should contain [REDACTED]: {}",
debug_output
);
}
#[test]
fn test_client_builder_returns_result() {
let result = Client::builder("test_key".to_string()).build();
assert!(result.is_ok());
}
#[test]
fn test_add_wire_inspector_accumulates() {
struct Noop;
impl WireInspector for Noop {
fn on_event(&self, _event: &crate::wire::WireEvent) {}
}
let client = Client::builder("test_key".to_string())
.add_wire_inspector(Arc::new(Noop))
.add_wire_inspector(Arc::new(Noop))
.build()
.unwrap();
assert_eq!(
client.http.inspectors.len(),
2,
"add_wire_inspector should accumulate, not replace"
);
}
#[test]
fn test_loud_wire_env_installs_printer() {
// SAFETY: test-only env mutation. No other test reads LOUD_WIRE, and
// an extra printer on an unrelated concurrently-built client is
// harmless (nothing sends requests in unit tests).
unsafe { std::env::set_var("LOUD_WIRE", "1") };
let with_env = Client::builder("test_key".to_string()).build().unwrap();
unsafe { std::env::remove_var("LOUD_WIRE") };
let without_env = Client::builder("test_key".to_string()).build().unwrap();
assert!(
with_env.http.has_inspectors(),
"LOUD_WIRE should install a LoudWirePrinter at construction"
);
assert!(
!without_env.http.has_inspectors(),
"no inspectors expected without LOUD_WIRE or add_wire_inspector"
);
}
#[test]
fn test_client_builder_debug_redacts_api_key() {
let builder = Client::builder("another_secret_key_67890".to_string())
.with_timeout(Duration::from_secs(60));
let debug_output = format!("{:?}", builder);
// API key should NOT appear in debug output
assert!(
!debug_output.contains("another_secret_key_67890"),
"API key was exposed in builder debug output: {}",
debug_output
);
// Should show [REDACTED] instead
assert!(
debug_output.contains("[REDACTED]"),
"Builder debug output should contain [REDACTED]: {}",
debug_output
);
}
#[tokio::test]
async fn test_upload_file_unknown_extension_error() {
let client = Client::new("test_key".to_string());
// Create a temp file with an unknown extension
let temp_dir = tempfile::tempdir().unwrap();
let file_path = temp_dir.path().join("data.xyz");
std::fs::write(&file_path, b"test data").unwrap();
// upload_file should fail with InvalidInput for unknown MIME type
let result = client.upload_file(&file_path).await;
assert!(result.is_err(), "Should fail for unknown extension");
let err = result.unwrap_err();
let err_string = err.to_string();
assert!(
err_string.contains("Could not determine MIME type"),
"Error should mention MIME type issue: {}",
err_string
);
assert!(
err_string.contains("data.xyz"),
"Error should include filename: {}",
err_string
);
}
#[tokio::test]
async fn test_upload_file_nonexistent_file_error() {
let client = Client::new("test_key".to_string());
// Try to upload a file that doesn't exist
let result = client.upload_file("/nonexistent/path/to/file.txt").await;
assert!(result.is_err(), "Should fail for nonexistent file");
let err = result.unwrap_err();
let err_string = err.to_string();
assert!(
err_string.contains("Failed to read file"),
"Error should mention file read failure: {}",
err_string
);
}
#[tokio::test]
async fn test_upload_file_bytes_empty_file_error() {
let client = Client::new("test_key".to_string());
// Try to upload empty bytes
let result = client
.upload_file_bytes(Vec::new(), "text/plain", Some("empty.txt"))
.await;
assert!(result.is_err(), "Should fail for empty file");
let err = result.unwrap_err();
let err_string = err.to_string();
assert!(
err_string.contains("Cannot upload empty file"),
"Error should mention empty file: {}",
err_string
);
}
#[tokio::test]
async fn test_upload_file_bytes_validates_before_network() {
// This test verifies that validation happens before any network call
// by using an invalid API key - if we reach the network, we'd get auth error
let client = Client::new("invalid_key".to_string());
// Empty file should fail with validation error, not auth error
let result = client
.upload_file_bytes(Vec::new(), "text/plain", None)
.await;
assert!(result.is_err());
let err_string = result.unwrap_err().to_string();
assert!(
err_string.contains("Cannot upload empty file"),
"Should fail validation before hitting network: {}",
err_string
);
}
}