openrouter-rs 0.5.2

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
use std::collections::HashMap;

use derive_builder::Builder;
use futures_util::{AsyncBufReadExt, StreamExt, stream::BoxStream};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use surf::http::headers::AUTHORIZATION;

use crate::{
    error::OpenRouterError,
    strip_option_map_setter, strip_option_vec_setter,
    types::{
        ProviderPreferences, ReasoningConfig, ResponseFormat, Role, completion::CompletionsResponse,
    },
    utils::handle_error,
};

/// Image URL with optional detail level for vision models.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ImageUrl {
    /// URL of the image (can be a web URL or base64 data URI)
    pub url: String,
    /// Detail level: "auto", "low", or "high"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

impl ImageUrl {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            detail: None,
        }
    }

    pub fn with_detail(url: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            detail: Some(detail.into()),
        }
    }
}

/// Audio input payload for multimodal requests.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct InputAudio {
    /// Base64-encoded audio data.
    pub data: String,
    /// Audio format (e.g. wav, mp3, flac).
    pub format: String,
}

impl InputAudio {
    pub fn new(data: impl Into<String>, format: impl Into<String>) -> Self {
        Self {
            data: data.into(),
            format: format.into(),
        }
    }
}

/// Video URL payload for multimodal requests.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VideoUrl {
    /// URL of the input video.
    pub url: String,
}

impl VideoUrl {
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }
}

/// File payload for multimodal requests.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct FileInput {
    /// File content as URL or data URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_data: Option<String>,
    /// File id for previously uploaded files.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_id: Option<String>,
    /// Optional filename metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
}

impl FileInput {
    pub fn from_data(file_data: impl Into<String>) -> Self {
        Self {
            file_data: Some(file_data.into()),
            file_id: None,
            filename: None,
        }
    }

    pub fn from_id(file_id: impl Into<String>) -> Self {
        Self {
            file_data: None,
            file_id: Some(file_id.into()),
            filename: None,
        }
    }

    pub fn filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }
}

/// Cache control type for prompt caching breakpoints.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum CacheControlType {
    Ephemeral,
}

/// Cache control settings for text content parts.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CacheControl {
    #[serde(rename = "type")]
    pub kind: CacheControlType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,
}

impl CacheControl {
    /// Create cache control using default ephemeral TTL.
    pub fn ephemeral() -> Self {
        Self {
            kind: CacheControlType::Ephemeral,
            ttl: None,
        }
    }

    /// Create cache control with explicit TTL (e.g. "1h").
    pub fn ephemeral_with_ttl(ttl: impl Into<String>) -> Self {
        Self {
            kind: CacheControlType::Ephemeral,
            ttl: Some(ttl.into()),
        }
    }
}

/// A content part in a multi-modal message.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    /// Text content
    Text {
        text: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// Image URL content
    ImageUrl { image_url: ImageUrl },
    /// Audio input content
    InputAudio { input_audio: InputAudio },
    /// Video URL content
    VideoUrl { video_url: VideoUrl },
    /// Legacy video input content
    InputVideo { video_url: VideoUrl },
    /// File content
    File { file: FileInput },
}

impl ContentPart {
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text {
            text: text.into(),
            cache_control: None,
        }
    }

    pub fn text_with_cache_control(text: impl Into<String>, cache_control: CacheControl) -> Self {
        Self::Text {
            text: text.into(),
            cache_control: Some(cache_control),
        }
    }

    pub fn cacheable_text(text: impl Into<String>) -> Self {
        Self::text_with_cache_control(text, CacheControl::ephemeral())
    }

    pub fn cacheable_text_with_ttl(text: impl Into<String>, ttl: impl Into<String>) -> Self {
        Self::text_with_cache_control(text, CacheControl::ephemeral_with_ttl(ttl))
    }

    pub fn image_url(url: impl Into<String>) -> Self {
        Self::ImageUrl {
            image_url: ImageUrl::new(url),
        }
    }

    pub fn image_url_with_detail(url: impl Into<String>, detail: impl Into<String>) -> Self {
        Self::ImageUrl {
            image_url: ImageUrl::with_detail(url, detail),
        }
    }

    pub fn input_audio(data: impl Into<String>, format: impl Into<String>) -> Self {
        Self::InputAudio {
            input_audio: InputAudio::new(data, format),
        }
    }

    pub fn video_url(url: impl Into<String>) -> Self {
        Self::VideoUrl {
            video_url: VideoUrl::new(url),
        }
    }

    pub fn input_video(url: impl Into<String>) -> Self {
        Self::InputVideo {
            video_url: VideoUrl::new(url),
        }
    }

    pub fn file_data(file_data: impl Into<String>) -> Self {
        Self::File {
            file: FileInput::from_data(file_data),
        }
    }

    pub fn file_data_with_filename(
        file_data: impl Into<String>,
        filename: impl Into<String>,
    ) -> Self {
        Self::File {
            file: FileInput::from_data(file_data).filename(filename),
        }
    }

    pub fn file_id(file_id: impl Into<String>) -> Self {
        Self::File {
            file: FileInput::from_id(file_id),
        }
    }

    pub fn file_id_with_filename(file_id: impl Into<String>, filename: impl Into<String>) -> Self {
        Self::File {
            file: FileInput::from_id(file_id).filename(filename),
        }
    }
}

/// Message content - either a simple string or multi-part content.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Content {
    /// Simple text content
    Text(String),
    /// Multi-part content (text, images, etc.)
    Parts(Vec<ContentPart>),
}

impl From<String> for Content {
    fn from(s: String) -> Self {
        Self::Text(s)
    }
}

impl From<&str> for Content {
    fn from(s: &str) -> Self {
        Self::Text(s.to_string())
    }
}

impl From<Vec<ContentPart>> for Content {
    fn from(parts: Vec<ContentPart>) -> Self {
        Self::Parts(parts)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Message {
    pub role: Role,
    pub content: Content,
    /// Optional name for tool messages or function calls
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Tool call ID for tool response messages
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// Tool calls made by assistant
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<crate::types::ToolCall>>,
}

impl Message {
    pub fn new(role: Role, content: impl Into<Content>) -> Self {
        Self {
            role,
            content: content.into(),
            name: None,
            tool_call_id: None,
            tool_calls: None,
        }
    }

    /// Create a message with multi-part content (text and images).
    pub fn with_parts(role: Role, parts: Vec<ContentPart>) -> Self {
        Self {
            role,
            content: Content::Parts(parts),
            name: None,
            tool_call_id: None,
            tool_calls: None,
        }
    }

    /// Create a tool response message
    pub fn tool_response(tool_call_id: &str, content: impl Into<Content>) -> Self {
        Self {
            role: Role::Tool,
            content: content.into(),
            name: None,
            tool_call_id: Some(tool_call_id.to_string()),
            tool_calls: None,
        }
    }

    /// Create a tool response message with a specific tool name
    pub fn tool_response_named(
        tool_call_id: &str,
        tool_name: &str,
        content: impl Into<Content>,
    ) -> Self {
        Self {
            role: Role::Tool,
            content: content.into(),
            name: Some(tool_name.to_string()),
            tool_call_id: Some(tool_call_id.to_string()),
            tool_calls: None,
        }
    }

    /// Create a message with a specific name
    pub fn named(role: Role, name: &str, content: impl Into<Content>) -> Self {
        Self {
            role,
            content: content.into(),
            name: Some(name.to_string()),
            tool_call_id: None,
            tool_calls: None,
        }
    }

    /// Create an assistant message with tool calls
    pub fn assistant_with_tool_calls(
        content: impl Into<Content>,
        tool_calls: Vec<crate::types::ToolCall>,
    ) -> Self {
        Self {
            role: Role::Assistant,
            content: content.into(),
            name: None,
            tool_call_id: None,
            tool_calls: Some(tool_calls),
        }
    }
}

/// Output modality for chat responses.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Modality {
    Text,
    Image,
    Audio,
}

/// Streaming debug options.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct DebugOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub echo_upstream_body: Option<bool>,
}

/// Streaming configuration options.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct StreamOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_usage: Option<bool>,
}

/// Trace metadata used for observability.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct TraceOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub span_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generation_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_span_id: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// Plugin configuration payload.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Plugin {
    pub id: String,
    #[serde(flatten)]
    pub config: HashMap<String, Value>,
}

impl Plugin {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            config: HashMap::new(),
        }
    }

    pub fn option(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.config.insert(key.into(), value.into());
        self
    }
}

/// Stop sequence configuration.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum StopSequence {
    Single(String),
    Multiple(Vec<String>),
}

impl From<String> for StopSequence {
    fn from(value: String) -> Self {
        Self::Single(value)
    }
}

impl From<&str> for StopSequence {
    fn from(value: &str) -> Self {
        Self::Single(value.to_string())
    }
}

impl From<Vec<String>> for StopSequence {
    fn from(value: Vec<String>) -> Self {
        Self::Multiple(value)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Builder)]
#[builder(build_fn(error = "OpenRouterError"))]
pub struct ChatCompletionRequest {
    #[builder(setter(into))]
    model: String,

    messages: Vec<Message>,

    #[builder(setter(skip), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    stream: Option<bool>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    max_tokens: Option<u32>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    max_completion_tokens: Option<u32>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f64>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    seed: Option<u32>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f64>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    top_k: Option<u32>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    frequency_penalty: Option<f64>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    presence_penalty: Option<f64>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    repetition_penalty: Option<f64>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    logit_bias: Option<HashMap<String, f64>>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    logprobs: Option<bool>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    top_logprobs: Option<u32>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    min_p: Option<f64>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    top_a: Option<f64>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    transforms: Option<Vec<String>>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    models: Option<Vec<String>>,

    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    route: Option<String>,

    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    user: Option<String>,

    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    session_id: Option<String>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    trace: Option<TraceOptions>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    provider: Option<ProviderPreferences>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<HashMap<String, String>>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    plugins: Option<Vec<Plugin>>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    modalities: Option<Vec<Modality>>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    image_config: Option<HashMap<String, Value>>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    response_format: Option<ResponseFormat>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    reasoning: Option<ReasoningConfig>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    include_reasoning: Option<bool>,

    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    stop: Option<StopSequence>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    stream_options: Option<StreamOptions>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    debug: Option<DebugOptions>,

    #[builder(setter(custom), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<crate::types::Tool>>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_choice: Option<crate::types::ToolChoice>,

    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    parallel_tool_calls: Option<bool>,
}

impl ChatCompletionRequestBuilder {
    strip_option_vec_setter!(models, String);
    strip_option_map_setter!(logit_bias, String, f64);
    strip_option_vec_setter!(transforms, String);
    strip_option_map_setter!(metadata, String, String);
    strip_option_map_setter!(image_config, String, Value);
    strip_option_vec_setter!(plugins, Plugin);
    strip_option_vec_setter!(modalities, Modality);
    strip_option_vec_setter!(tools, crate::types::Tool);

    /// Enable reasoning with default settings (medium effort)
    pub fn enable_reasoning(&mut self) -> &mut Self {
        use crate::types::ReasoningConfig;
        self.reasoning = Some(Some(ReasoningConfig::enabled()));
        self
    }

    /// Set reasoning effort level
    pub fn reasoning_effort(&mut self, effort: crate::types::Effort) -> &mut Self {
        use crate::types::ReasoningConfig;
        self.reasoning = Some(Some(ReasoningConfig::with_effort(effort)));
        self
    }

    /// Set reasoning max tokens
    pub fn reasoning_max_tokens(&mut self, max_tokens: u32) -> &mut Self {
        use crate::types::ReasoningConfig;
        self.reasoning = Some(Some(ReasoningConfig::with_max_tokens(max_tokens)));
        self
    }

    /// Exclude reasoning from response (use reasoning internally but don't return it)
    pub fn exclude_reasoning(&mut self) -> &mut Self {
        use crate::types::ReasoningConfig;
        self.reasoning = Some(Some(ReasoningConfig::excluded()));
        self
    }

    /// Add a single tool to the request
    pub fn tool(&mut self, tool: crate::types::Tool) -> &mut Self {
        if let Some(Some(ref mut existing_tools)) = self.tools {
            existing_tools.push(tool);
        } else {
            self.tools = Some(Some(vec![tool]));
        }
        self
    }

    /// Set tool choice to auto (model chooses whether to use tools)
    pub fn tool_choice_auto(&mut self) -> &mut Self {
        self.tool_choice = Some(Some(crate::types::ToolChoice::auto()));
        self
    }

    /// Set tool choice to none (model will not use tools)
    pub fn tool_choice_none(&mut self) -> &mut Self {
        self.tool_choice = Some(Some(crate::types::ToolChoice::none()));
        self
    }

    /// Set tool choice to required (model must use tools)
    pub fn tool_choice_required(&mut self) -> &mut Self {
        self.tool_choice = Some(Some(crate::types::ToolChoice::required()));
        self
    }

    /// Force the model to use a specific tool
    pub fn force_tool(&mut self, tool_name: &str) -> &mut Self {
        self.tool_choice = Some(Some(crate::types::ToolChoice::force_tool(tool_name)));
        self
    }

    /// Add a typed tool to the request
    ///
    /// This method allows adding strongly-typed tools using the TypedTool trait.
    /// The tool's JSON Schema is automatically generated from the Rust type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use openrouter_rs::types::typed_tool::TypedTool;
    /// use serde::{Deserialize, Serialize};
    /// use schemars::JsonSchema;
    ///
    /// #[derive(Serialize, Deserialize, JsonSchema)]
    /// struct WeatherParams {
    ///     location: String,
    /// }
    ///
    /// impl TypedTool for WeatherParams {
    ///     fn name() -> &'static str { "get_weather" }
    ///     fn description() -> &'static str { "Get weather for location" }
    /// }
    ///
    /// let request = ChatCompletionRequest::builder()
    ///     .model("anthropic/claude-sonnet-4")
    ///     .typed_tool::<WeatherParams>()
    ///     .build()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn typed_tool<T: crate::types::TypedTool>(&mut self) -> &mut Self {
        let tool = T::create_tool();
        self.tool(tool)
    }

    /// Add multiple typed tools to the request
    ///
    /// This is a convenience method for adding multiple typed tools at once.
    /// Each tool type must implement the TypedTool trait.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use openrouter_rs::types::typed_tool::TypedTool;
    /// # use serde::{Deserialize, Serialize};
    /// # use schemars::JsonSchema;
    /// # #[derive(Serialize, Deserialize, JsonSchema)]
    /// # struct WeatherParams { location: String }
    /// # impl TypedTool for WeatherParams {
    /// #     fn name() -> &'static str { "get_weather" }
    /// #     fn description() -> &'static str { "Get weather" }
    /// # }
    /// # #[derive(Serialize, Deserialize, JsonSchema)]
    /// # struct CalculatorParams { a: f64, b: f64 }
    /// # impl TypedTool for CalculatorParams {
    /// #     fn name() -> &'static str { "calculator" }
    /// #     fn description() -> &'static str { "Calculate" }
    /// # }
    ///
    /// let request = ChatCompletionRequest::builder()
    ///     .model("anthropic/claude-sonnet-4")
    ///     .typed_tools_batch(&[
    ///         WeatherParams::create_tool(),
    ///         CalculatorParams::create_tool(),
    ///     ])
    ///     .build()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn typed_tools_batch(&mut self, tools: &[crate::types::Tool]) -> &mut Self {
        for tool in tools {
            self.tool(tool.clone());
        }
        self
    }

    /// Force the model to use a specific typed tool
    ///
    /// This method combines the typed tool functionality with tool choice forcing.
    /// The specified typed tool will be added to the tools list and forced as the choice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use openrouter_rs::types::typed_tool::TypedTool;
    /// # use serde::{Deserialize, Serialize};
    /// # use schemars::JsonSchema;
    /// # #[derive(Serialize, Deserialize, JsonSchema)]
    /// # struct WeatherParams { location: String }
    /// # impl TypedTool for WeatherParams {
    /// #     fn name() -> &'static str { "get_weather" }
    /// #     fn description() -> &'static str { "Get weather" }
    /// # }
    ///
    /// let request = ChatCompletionRequest::builder()
    ///     .model("anthropic/claude-sonnet-4")
    ///     .force_typed_tool::<WeatherParams>()
    ///     .build()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn force_typed_tool<T: crate::types::TypedTool>(&mut self) -> &mut Self {
        let tool_name = T::name();
        let tool = T::create_tool();
        self.tool(tool);
        self.force_tool(tool_name);
        self
    }
}

impl ChatCompletionRequest {
    pub fn builder() -> ChatCompletionRequestBuilder {
        ChatCompletionRequestBuilder::default()
    }

    pub fn new(model: &str, messages: Vec<Message>) -> Self {
        Self::builder()
            .model(model)
            .messages(messages)
            .build()
            .expect("Failed to build ChatCompletionRequest")
    }

    /// Get the tools defined in this request
    pub fn tools(&self) -> Option<&Vec<crate::types::Tool>> {
        self.tools.as_ref()
    }

    /// Get the tool choice setting
    pub fn tool_choice(&self) -> Option<&crate::types::ToolChoice> {
        self.tool_choice.as_ref()
    }

    /// Get the parallel tool calls setting
    pub fn parallel_tool_calls(&self) -> Option<bool> {
        self.parallel_tool_calls
    }

    /// Get the messages in this request
    pub fn messages(&self) -> &Vec<Message> {
        &self.messages
    }

    fn stream(&self, stream: bool) -> Self {
        let mut req = self.clone();
        req.stream = Some(stream);
        req
    }
}

/// Send a chat completion request to a selected model.
///
/// # Arguments
///
/// * `base_url` - The base URL for the OpenRouter API.
/// * `api_key` - The API key for authentication.
/// * `x_title` - The name of the site for the request.
/// * `http_referer` - The URL of the site for the request.
/// * `request` - The chat completion request containing the model and messages.
///
/// # Returns
///
/// * `Result<CompletionsResponse, OpenRouterError>` - The response from the chat completion request.
pub async fn send_chat_completion(
    base_url: &str,
    api_key: &str,
    x_title: &Option<String>,
    http_referer: &Option<String>,
    request: &ChatCompletionRequest,
) -> Result<CompletionsResponse, OpenRouterError> {
    let url = format!("{base_url}/chat/completions");

    // Ensure that the request is not streaming to get a single response
    let request = request.stream(false);

    let mut surf_req = surf::post(url)
        .header(AUTHORIZATION, format!("Bearer {api_key}"))
        .body_json(&request)?;

    if let Some(x_title) = x_title {
        surf_req = surf_req.header("X-Title", x_title);
    }
    if let Some(http_referer) = http_referer {
        surf_req = surf_req.header("HTTP-Referer", http_referer);
    }

    let mut response = surf_req.await?;

    if response.status().is_success() {
        let body_text = response.body_string().await?;
        let chat_response: CompletionsResponse = serde_json::from_str(&body_text).map_err(|e| {
            eprintln!("Failed to deserialize response: {e}\nBody: {body_text}");
            OpenRouterError::Serialization(e)
        })?;
        Ok(chat_response)
    } else {
        handle_error(response).await?;
        unreachable!()
    }
}

/// Stream chat completion events from a selected model.
///
/// # Arguments
///
/// * `base_url` - The base URL for the OpenRouter API.
/// * `api_key` - The API key for authentication.
/// * `request` - The chat completion request containing the model and messages.
///
/// # Returns
///
/// * `Result<BoxStream<'static, Result<CompletionsResponse, OpenRouterError>>, OpenRouterError>` - A stream of chat completion events or an error.
pub async fn stream_chat_completion(
    base_url: &str,
    api_key: &str,
    request: &ChatCompletionRequest,
) -> Result<BoxStream<'static, Result<CompletionsResponse, OpenRouterError>>, OpenRouterError> {
    let url = format!("{base_url}/chat/completions");

    // Ensure that the request is streaming to get a continuous response
    let request = request.stream(true);

    let response = surf::post(url)
        .header(AUTHORIZATION, format!("Bearer {api_key}"))
        .body_json(&request)?
        .await?;

    if response.status().is_success() {
        let lines = response
            .lines()
            .filter_map(async |line| match line {
                Ok(line) => line
                    .strip_prefix("data: ")
                    .filter(|line| *line != "[DONE]")
                    .map(serde_json::from_str::<CompletionsResponse>)
                    .map(|event| event.map_err(OpenRouterError::Serialization)),
                Err(error) => Some(Err(OpenRouterError::Io(error))),
            })
            .boxed();

        Ok(lines)
    } else {
        handle_error(response).await?;
        unreachable!()
    }
}