openrouter-rs 0.11.0

A type-safe OpenRouter Rust SDK
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
use std::collections::HashMap;

use derive_builder::Builder;
use reqwest::Client as HttpClient;
use serde::{Deserialize, Serialize};
use urlencoding::encode;

use crate::{
    api::models::ModelReasoning,
    error::OpenRouterError,
    transport::{request as transport_request, response as transport_response},
    types::ApiResponse,
};

/// Number-like value used by OpenRouter pricing fields.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[non_exhaustive]
#[serde(untagged)]
pub enum BigNumber {
    String(String),
    Number(f64),
}

/// Public provider metadata returned by `GET /providers`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Provider {
    pub name: String,
    pub slug: String,
    pub privacy_policy_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terms_of_service_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_page_url: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Model pricing payload returned by model discovery endpoints.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct PublicPricing {
    pub prompt: BigNumber,
    pub completion: BigNumber,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_token: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_output: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio_output: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_audio_cache: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web_search: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub internal_reasoning: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_cache_read: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_cache_write: Option<BigNumber>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub discount: Option<f64>,
}

/// Model architecture data in model discovery responses.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct ModelArchitecture {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokenizer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instruct_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modality: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_modalities: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_modalities: Option<Vec<String>>,
}

/// Top provider metadata in model discovery responses.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TopProviderInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_length: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<f64>,
    pub is_moderated: bool,
}

/// Per-request token limits for a model.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct PerRequestLimits {
    pub prompt_tokens: f64,
    pub completion_tokens: f64,
}

/// Model payload returned by `GET /models/user`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UserModel {
    pub id: String,
    pub canonical_slug: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hugging_face_id: Option<String>,
    pub name: String,
    pub created: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub pricing: PublicPricing,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_length: Option<f64>,
    pub architecture: ModelArchitecture,
    pub top_provider: TopProviderInfo,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub per_request_limits: Option<PerRequestLimits>,
    #[serde(default)]
    pub supported_parameters: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supported_voices: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_parameters: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration_date: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ModelReasoning>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Count payload returned by `GET /models/count`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct ModelsCountData {
    pub count: u64,
}

/// Percentile statistics payload used by endpoint throughput/latency.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct PercentileStats {
    pub p50: f64,
    pub p75: f64,
    pub p90: f64,
    pub p99: f64,
}

/// Public endpoint payload returned by `GET /endpoints/zdr`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct PublicEndpoint {
    pub name: String,
    pub model_id: String,
    pub model_name: String,
    pub context_length: f64,
    pub pricing: PublicPricing,
    pub provider_name: String,
    pub tag: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantization: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_prompt_tokens: Option<f64>,
    #[serde(default)]
    pub supported_parameters: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uptime_last_30m: Option<f64>,
    pub supports_implicit_caching: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency_last_30m: Option<PercentileStats>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub throughput_last_30m: Option<PercentileStats>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Activity item payload returned by `GET /activity`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct ActivityItem {
    pub date: String,
    pub model: String,
    pub model_permaslug: String,
    pub endpoint_id: String,
    pub provider_name: String,
    pub usage: f64,
    pub byok_usage_inference: f64,
    pub requests: f64,
    pub prompt_tokens: f64,
    pub completion_tokens: f64,
    pub reasoning_tokens: f64,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// One daily model-ranking row returned by `GET /datasets/rankings-daily`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct RankingsDailyItem {
    pub date: String,
    pub model_permaslug: String,
    pub total_tokens: String,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Metadata for a daily rankings dataset response.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct RankingsDailyMeta {
    pub as_of: String,
    pub version: String,
    pub start_date: String,
    pub end_date: String,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Daily token totals for top public models plus an aggregated `other` row.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct RankingsDailyResponse {
    pub data: Vec<RankingsDailyItem>,
    pub meta: RankingsDailyMeta,
}

/// Query parameters for `GET /datasets/app-rankings`.
#[derive(Serialize, Deserialize, Debug, Clone, Default, Builder)]
#[builder(build_fn(error = "OpenRouterError"))]
#[non_exhaustive]
pub struct AppRankingsParams {
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subcategory: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_date: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_date: Option<String>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

impl AppRankingsParams {
    pub fn builder() -> AppRankingsParamsBuilder {
        AppRankingsParamsBuilder::default()
    }

    fn is_empty(&self) -> bool {
        self.category.is_none()
            && self.subcategory.is_none()
            && self.sort.is_none()
            && self.start_date.is_none()
            && self.end_date.is_none()
            && self.limit.is_none()
            && self.offset.is_none()
    }
}

/// One application ranking row returned by `GET /datasets/app-rankings`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct AppRankingsItem {
    pub rank: u64,
    pub app_id: u64,
    pub app_name: String,
    pub total_tokens: String,
    pub total_requests: u64,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// App rankings dataset response.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct AppRankingsResponse {
    pub data: Vec<AppRankingsItem>,
    pub meta: RankingsDailyMeta,
}

/// Top model share for one task classification.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TaskClassificationModel {
    pub id: String,
    pub tag_usage_share: f64,
    pub tag_token_share: f64,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// One task classification row returned by `GET /classifications/task`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TaskClassificationItem {
    pub tag: String,
    pub display_name: String,
    pub macro_category: String,
    pub usage_share: f64,
    pub token_share: f64,
    pub category_usage_share: f64,
    pub category_token_share: f64,
    pub models: Vec<TaskClassificationModel>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Aggregate market-share data for one task macro-category.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TaskClassificationMacroCategory {
    pub key: String,
    pub label: String,
    pub usage_share: f64,
    pub token_share: f64,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Data payload returned by `GET /classifications/task`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TaskClassificationsData {
    pub window_days: u64,
    pub as_of: String,
    pub classifications: Vec<TaskClassificationItem>,
    pub macro_categories: Vec<TaskClassificationMacroCategory>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Task classification response returned by `GET /classifications/task`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TaskClassificationsResponse {
    pub data: TaskClassificationsData,
}

/// OpenRouter benchmark pricing payload.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarkPricing {
    pub prompt: String,
    pub completion: String,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// One Artificial Analysis benchmark row.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarksAAItem {
    pub model_permaslug: String,
    pub aa_name: String,
    pub intelligence_index: Option<f64>,
    pub coding_index: Option<f64>,
    pub agentic_index: Option<f64>,
    pub pricing: Option<BenchmarkPricing>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Metadata for Artificial Analysis benchmark rows.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarksAAMeta {
    pub as_of: String,
    pub version: String,
    pub source: String,
    pub source_url: String,
    pub citation: String,
    pub model_count: u64,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Artificial Analysis benchmark dataset response.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarksAAResponse {
    pub data: Vec<BenchmarksAAItem>,
    pub meta: BenchmarksAAMeta,
}

/// Placement distribution from Design Arena tournament matches.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct DesignArenaTournamentStats {
    pub first_place: Option<u64>,
    pub second_place: Option<u64>,
    pub third_place: Option<u64>,
    pub fourth_place: Option<u64>,
    pub total: Option<u64>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// One Design Arena benchmark row.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarksDAItem {
    pub model_permaslug: String,
    pub display_name: String,
    pub arena: String,
    pub category: String,
    pub elo: f64,
    pub win_rate: f64,
    pub avg_generation_time_ms: Option<f64>,
    pub tournament_stats: DesignArenaTournamentStats,
    pub pricing: Option<BenchmarkPricing>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// ELO bounds for a Design Arena response.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct DesignArenaEloBounds {
    pub min: f64,
    pub max: f64,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Metadata for Design Arena benchmark rows.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarksDAMeta {
    pub as_of: String,
    pub version: String,
    pub source: String,
    pub source_url: String,
    pub citation: String,
    pub model_count: u64,
    pub arena: String,
    pub category: Option<String>,
    pub elo_bounds: DesignArenaEloBounds,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Design Arena benchmark dataset response.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BenchmarksDAResponse {
    pub data: Vec<BenchmarksDAItem>,
    pub meta: BenchmarksDAMeta,
}

/// Query parameters for the unified benchmarks endpoint.
#[derive(Serialize, Deserialize, Debug, Clone, Default, Builder)]
#[builder(build_fn(error = "OpenRouterError"))]
#[non_exhaustive]
pub struct UnifiedBenchmarksParams {
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_type: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arena: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_results: Option<u32>,
}

impl UnifiedBenchmarksParams {
    pub fn builder() -> UnifiedBenchmarksParamsBuilder {
        UnifiedBenchmarksParamsBuilder::default()
    }

    pub fn artificial_analysis() -> Self {
        Self {
            source: Some("artificial-analysis".to_string()),
            task_type: None,
            arena: None,
            category: None,
            max_results: None,
        }
    }

    pub fn design_arena() -> Self {
        Self {
            source: Some("design-arena".to_string()),
            task_type: None,
            arena: None,
            category: None,
            max_results: None,
        }
    }
}

/// One Artificial Analysis row returned by `GET /benchmarks`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UnifiedBenchmarksAAItem {
    pub source: String,
    pub model_permaslug: String,
    pub display_name: String,
    pub intelligence_index: Option<f64>,
    pub coding_index: Option<f64>,
    pub agentic_index: Option<f64>,
    pub pricing: Option<BenchmarkPricing>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// One Design Arena row returned by `GET /benchmarks`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UnifiedBenchmarksDAItem {
    pub source: String,
    pub model_permaslug: String,
    pub display_name: String,
    pub arena: String,
    pub category: String,
    pub elo: f64,
    pub win_rate: f64,
    pub avg_generation_time_ms: Option<f64>,
    pub tournament_stats: DesignArenaTournamentStats,
    pub pricing: Option<BenchmarkPricing>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// One benchmark row returned by `GET /benchmarks`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
#[non_exhaustive]
pub enum UnifiedBenchmarkItem {
    DesignArena(UnifiedBenchmarksDAItem),
    ArtificialAnalysis(UnifiedBenchmarksAAItem),
    Other(HashMap<String, serde_json::Value>),
}

/// Metadata for the unified benchmarks endpoint.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UnifiedBenchmarksMeta {
    pub as_of: String,
    pub version: String,
    pub source: Option<String>,
    pub source_url: Option<String>,
    pub citation: Option<String>,
    pub model_count: u64,
    pub task_type: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Unified benchmark response returned by `GET /benchmarks`.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UnifiedBenchmarksResponse {
    pub data: Vec<UnifiedBenchmarkItem>,
    pub meta: UnifiedBenchmarksMeta,
}

/// List all providers (`GET /providers`).
pub async fn list_providers(
    base_url: &str,
    api_key: &str,
) -> Result<Vec<Provider>, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    list_providers_with_client(&http_client, base_url, api_key).await
}

pub(crate) async fn list_providers_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
) -> Result<Vec<Provider>, OpenRouterError> {
    let url = format!("{base_url}/providers");
    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .send()
            .await?;

    if response.status().is_success() {
        let parsed: ApiResponse<Vec<Provider>> =
            transport_response::parse_json_response(response, "provider list").await?;
        Ok(parsed.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// List models filtered by user settings (`GET /models/user`).
pub async fn list_models_for_user(
    base_url: &str,
    api_key: &str,
) -> Result<Vec<UserModel>, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    list_models_for_user_with_client(&http_client, base_url, api_key).await
}

pub(crate) async fn list_models_for_user_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
) -> Result<Vec<UserModel>, OpenRouterError> {
    let url = format!("{base_url}/models/user");
    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .send()
            .await?;

    if response.status().is_success() {
        let parsed: ApiResponse<Vec<UserModel>> =
            transport_response::parse_json_response(response, "user model list").await?;
        Ok(parsed.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Count available models (`GET /models/count`).
pub async fn count_models(
    base_url: &str,
    api_key: &str,
) -> Result<ModelsCountData, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    count_models_with_client(&http_client, base_url, api_key).await
}

pub(crate) async fn count_models_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
) -> Result<ModelsCountData, OpenRouterError> {
    let url = format!("{base_url}/models/count");
    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .send()
            .await?;

    if response.status().is_success() {
        let parsed: ApiResponse<ModelsCountData> =
            transport_response::parse_json_response(response, "model count").await?;
        Ok(parsed.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Return daily token totals for top public models (`GET /datasets/rankings-daily`).
pub async fn get_rankings_daily(
    base_url: &str,
    api_key: &str,
    start_date: Option<&str>,
    end_date: Option<&str>,
) -> Result<RankingsDailyResponse, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_rankings_daily_with_client(&http_client, base_url, api_key, start_date, end_date).await
}

pub(crate) async fn get_rankings_daily_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    start_date: Option<&str>,
    end_date: Option<&str>,
) -> Result<RankingsDailyResponse, OpenRouterError> {
    #[derive(Serialize)]
    struct RankingsDailyQuery<'a> {
        #[serde(skip_serializing_if = "Option::is_none")]
        start_date: Option<&'a str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        end_date: Option<&'a str>,
    }

    let url = format!("{base_url}/datasets/rankings-daily");
    let query = RankingsDailyQuery {
        start_date,
        end_date,
    };
    let req =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key);
    let response = if query.start_date.is_none() && query.end_date.is_none() {
        req.send().await?
    } else {
        req.query(&query).send().await?
    };

    if response.status().is_success() {
        transport_response::parse_json_response(response, "rankings daily").await
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Return app rankings over a date window (`GET /datasets/app-rankings`).
pub async fn get_app_rankings(
    base_url: &str,
    api_key: &str,
    params: Option<&AppRankingsParams>,
) -> Result<AppRankingsResponse, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_app_rankings_with_client(&http_client, base_url, api_key, params).await
}

pub(crate) async fn get_app_rankings_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    params: Option<&AppRankingsParams>,
) -> Result<AppRankingsResponse, OpenRouterError> {
    let url = format!("{base_url}/datasets/app-rankings");
    let req =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key);
    let response = match params {
        Some(params) if !params.is_empty() => req.query(params).send().await?,
        _ => req.send().await?,
    };

    if response.status().is_success() {
        transport_response::parse_json_response(response, "app rankings").await
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Return task classification market-share data (`GET /classifications/task`).
pub async fn get_task_classifications(
    base_url: &str,
    api_key: &str,
    window: Option<&str>,
) -> Result<TaskClassificationsResponse, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_task_classifications_with_client(&http_client, base_url, api_key, window).await
}

pub(crate) async fn get_task_classifications_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    window: Option<&str>,
) -> Result<TaskClassificationsResponse, OpenRouterError> {
    let url = format!("{base_url}/classifications/task");
    let req =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key);
    let response = match window {
        Some(window) => req.query(&[("window", window)]).send().await?,
        None => req.send().await?,
    };

    if response.status().is_success() {
        transport_response::parse_json_response(response, "task classifications").await
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Return benchmark rows from a selected benchmark source (`GET /benchmarks`).
pub async fn get_benchmarks(
    base_url: &str,
    api_key: &str,
    params: &UnifiedBenchmarksParams,
) -> Result<UnifiedBenchmarksResponse, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_benchmarks_with_client(&http_client, base_url, api_key, params).await
}

pub(crate) async fn get_benchmarks_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    params: &UnifiedBenchmarksParams,
) -> Result<UnifiedBenchmarksResponse, OpenRouterError> {
    let url = format!("{base_url}/benchmarks");
    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .query(params)
            .send()
            .await?;

    if response.status().is_success() {
        transport_response::parse_json_response(response, "benchmarks").await
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

#[derive(Serialize)]
struct BenchmarkMaxResultsQuery {
    #[serde(skip_serializing_if = "Option::is_none")]
    max_results: Option<u32>,
}

/// Return Artificial Analysis benchmark rows.
#[deprecated(note = "use get_benchmarks with source `artificial-analysis`")]
pub async fn get_benchmarks_artificial_analysis(
    base_url: &str,
    api_key: &str,
    max_results: Option<u32>,
) -> Result<BenchmarksAAResponse, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_benchmarks_artificial_analysis_with_client(&http_client, base_url, api_key, max_results)
        .await
}

pub(crate) async fn get_benchmarks_artificial_analysis_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    max_results: Option<u32>,
) -> Result<BenchmarksAAResponse, OpenRouterError> {
    let url = format!("{base_url}/datasets/benchmarks/artificial-analysis");
    let query = BenchmarkMaxResultsQuery { max_results };
    let req =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key);
    let response = if query.max_results.is_none() {
        req.send().await?
    } else {
        req.query(&query).send().await?
    };

    if response.status().is_success() {
        transport_response::parse_json_response(response, "Artificial Analysis benchmarks").await
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

#[derive(Serialize)]
struct DesignArenaQuery<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    arena: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    category: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_results: Option<u32>,
}

/// Return Design Arena benchmark rows.
#[deprecated(note = "use get_benchmarks with source `design-arena`")]
pub async fn get_benchmarks_design_arena(
    base_url: &str,
    api_key: &str,
    arena: Option<&str>,
    category: Option<&str>,
    max_results: Option<u32>,
) -> Result<BenchmarksDAResponse, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_benchmarks_design_arena_with_client(
        &http_client,
        base_url,
        api_key,
        arena,
        category,
        max_results,
    )
    .await
}

pub(crate) async fn get_benchmarks_design_arena_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    arena: Option<&str>,
    category: Option<&str>,
    max_results: Option<u32>,
) -> Result<BenchmarksDAResponse, OpenRouterError> {
    let url = format!("{base_url}/datasets/benchmarks/design-arena");
    let query = DesignArenaQuery {
        arena,
        category,
        max_results,
    };
    let req =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key);
    let response =
        if query.arena.is_none() && query.category.is_none() && query.max_results.is_none() {
            req.send().await?
        } else {
            req.query(&query).send().await?
        };

    if response.status().is_success() {
        transport_response::parse_json_response(response, "Design Arena benchmarks").await
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// List ZDR-compatible endpoints (`GET /endpoints/zdr`).
pub async fn list_zdr_endpoints(
    base_url: &str,
    api_key: &str,
) -> Result<Vec<PublicEndpoint>, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    list_zdr_endpoints_with_client(&http_client, base_url, api_key).await
}

pub(crate) async fn list_zdr_endpoints_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
) -> Result<Vec<PublicEndpoint>, OpenRouterError> {
    let url = format!("{base_url}/endpoints/zdr");
    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .send()
            .await?;

    if response.status().is_success() {
        let parsed: ApiResponse<Vec<PublicEndpoint>> =
            transport_response::parse_json_response(response, "ZDR endpoint list").await?;
        Ok(parsed.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Get endpoint-grouped activity (`GET /activity`).
///
/// `date` is optional and should be in `YYYY-MM-DD` format.
pub async fn get_activity(
    base_url: &str,
    management_key: &str,
    date: Option<&str>,
) -> Result<Vec<ActivityItem>, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_activity_with_client(&http_client, base_url, management_key, date).await
}

pub(crate) async fn get_activity_with_client(
    http_client: &HttpClient,
    base_url: &str,
    management_key: &str,
    date: Option<&str>,
) -> Result<Vec<ActivityItem>, OpenRouterError> {
    let url = if let Some(date) = date {
        format!("{base_url}/activity?date={}", encode(date))
    } else {
        format!("{base_url}/activity")
    };

    let response = transport_request::with_bearer_auth(
        transport_request::get(http_client, &url),
        management_key,
    )
    .send()
    .await?;

    if response.status().is_success() {
        let parsed: ApiResponse<Vec<ActivityItem>> =
            transport_response::parse_json_response(response, "activity list").await?;
        Ok(parsed.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}