anthropik 0.1.3

Anthropic client for Rust.
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
use std::borrow::Cow;
use std::fmt::Display;
use std::pin::Pin;

use bytes::Bytes;
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
pub enum ApiVersion {
    #[default]
    Latest,
    #[serde(rename = "2023-06-01")]
    V2023_06_01,
    #[serde(rename = "2023-01-01")]
    V2023_01_01,
}

impl AsRef<str> for ApiVersion {
    fn as_ref(&self) -> &str {
        match self {
            Self::Latest => "2023-06-01",
            Self::V2023_06_01 => "2023-06-01",
            Self::V2023_01_01 => "2023-01-01",
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum Model {
    #[serde(rename = "claude-sonnet-4-5-20250929")]
    ClaudeSonnet4_5,
    #[serde(rename = "claude-haiku-4-5-20251001")]
    ClaudeHaiku4_5,
    #[serde(rename = "claude-opus-4-5-20251101")]
    ClaudeOpus4_5,
    #[serde(rename = "claude-opus-4-1-20250805")]
    ClaudeOpus4_1,
    #[serde(rename = "claude-opus-4-20250514")]
    ClaudeOpus4,
    #[serde(rename = "claude-sonnet-4-20250514")]
    ClaudeSonnet4,
    #[serde(rename = "claude-3-7-sonnet-20250219")]
    ClaudeSonnet3_7,
    #[serde(rename = "claude-3-5-sonnet-20241022")]
    ClaudeSonnet3_5V2,
    #[serde(rename = "claude-3-5-sonnet-20240620")]
    ClaudeSonnet3_5,
    #[serde(rename = "claude-3-5-haiku-20241022")]
    ClaudeHaiku3_5,
    #[serde(rename = "claude-3-haiku-20240307")]
    ClaudeHaiku3,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    User,
    Assistant,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Content {
    String(String),
    Blocks(Vec<ContentBlock>),
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum ContentBlock {
    Text {
        text: String,
        #[serde(default)]
        cache_control: Option<CacheControl>,
        #[serde(default)]
        citations: Option<Vec<Citation>>,
    },
    Image {
        source: ImageSource,
        #[serde(default)]
        cache_control: Option<CacheControl>,
    },
    Document {
        source: DocumentSource,
        #[serde(default)]
        cache_control: Option<CacheControl>,
        #[serde(default)]
        citations: Option<Vec<Citation>>,
        #[serde(default)]
        context: Option<String>,
        #[serde(default)]
        title: Option<String>,
    },
    ToolUse {
        id: String,
        input: serde_json::Value,
        name: String,
        #[serde(default)]
        cache_control: Option<CacheControl>,
    },
    ToolResult {
        tool_use_id: String,
        #[serde(default)]
        cache_control: Option<CacheControl>,
        #[serde(default)]
        content: Option<Vec<ToolResultContentBlock>>,
        #[serde(default)]
        is_error: Option<bool>,
    },
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum ToolResultContentBlock {
    Text { text: String },
    Image { source: ImageSource },
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum ContentBlockDelta {
    TextDelta { text: String },
    InputJsonDelta { partial_json: String },
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum CacheControl {
    /// The time-to-live for the cache control breakpoint.
    Ephemeral { ttl: Ttl },
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum Ttl {
    FiveMinutes,
    OneHour,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Citation {
    CharacterLocation {
        cited_text: String,
        document_index: u32,
        document_title: Option<String>,
        end_char_index: u32,
        start_char_index: u32,
    },
    PageLocation {
        cited_text: String,
        document_index: u32,
        document_title: Option<String>,
        end_page_number: u32,
        start_page_number: u32,
    },
    ContentBlockLocation {
        cited_text: String,
        document_index: u32,
        document_title: Option<String>,
        end_block_index: u32,
        start_block_index: u32,
    },
    RequestWebSearchResultLocationCitation {
        cited_text: String,
        encrypted_index: String,
        title: Option<String>,
        url: String,
    },
    RequestSerarchResultLocationCitation {
        cited_text: String,
        end_block_index: u32,
        search_result_index: u32,
        source: String,
        start_block_index: u32,
        title: Option<String>,
    },
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum ImageSource {
    Base64 {
        data: String,
        media_type: ImageMediaType,
    },
    Url {
        url: String,
    },
    File {
        file_id: String,
    },
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum DocumentSource {
    PdfBase64 {
        data: String,
        media_type: DocumentMediaType,
    },
    PlainText {
        data: String,
        media_type: DocumentMediaType,
    },
    ContentBlock {
        content: Content,
    },
    PdfUrl {
        url: String,
    },
    FileDocument {
        file_id: String,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum DocumentMediaType {
    Pdf,
    Plain,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum ImageMediaType {
    Jpeg,
    Png,
    Gif,
    Webp,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct InputMessage {
    pub role: Role,
    pub content: Content,
    #[serde(skip)]
    pub _ne: (),
}

impl Default for InputMessage {
    fn default() -> Self {
        Self {
            role: Role::User,
            content: Content::String(String::new()),
            _ne: (),
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct McpServer {
    pub name: String,
    pub url: String,
    pub authorization_token: Option<String>,
    pub tool_configuration: Option<ToolConfiguration>,
    #[serde(skip)]
    _ne: (),
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct ToolConfiguration {
    pub allowed_tools: Option<Vec<String>>,
    pub enabled: Option<bool>,
    #[serde(skip)]
    _ne: (),
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct Metadata<'a> {
    /// An external identifier for the user who is associated with the request.
    pub user_id: Option<Cow<'a, str>>,
    #[serde(skip)]
    _ne: (),
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum ServiceTier {
    Auto,
    StandardOnly,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum Thinking {
    Enabled {
        /// Determines how many tokens Claude can use for its internal reasoning process.
        budget_tokens: u32,
    },
    Disabled,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum ToolChoice {
    Auto {
        /// Whether to disable parallel tool use.
        disable_parallel_tool_use: bool,
    },
    Any {
        /// Whether to disable parallel tool use.
        disable_parallel_tool_use: bool,
    },
    Tool {
        /// The name of the tool to use.
        tool_name: String,
        /// Whether to disable parallel tool use.
        disable_parallel_tool_use: bool,
    },
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type", rename = "object")]
#[allow(clippy::manual_non_exhaustive)]
pub struct InputSchema {
    pub properties: Option<serde_json::Value>,
    pub required: Option<Vec<String>>,
    #[serde(skip)]
    pub _ne: (),
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct Tool<'a> {
    /// Name of the tool.
    pub name: Cow<'a, str>,
    /// JSON schema for this tool's input.
    pub input_schema: InputSchema,
    /// Description of what this tool does.
    pub description: Option<Cow<'a, str>>,
    /// Create a cache control breakpoint at this content block.
    pub cache_control: Option<CacheControl>,
    #[serde(skip)]
    pub _ne: (),
}

impl Default for Tool<'_> {
    fn default() -> Self {
        Self {
            name: Cow::Borrowed(""),
            input_schema: InputSchema::default(),
            description: None,
            cache_control: None,
            _ne: (),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct MessagesRequest<'a> {
    /// Optional header to specify the beta version(s) you want to use.
    #[serde(skip)]
    pub anthropic_beta: Option<Vec<Cow<'a, str>>>,
    /// The version of the Anthropic API you want to use.
    #[serde(skip)]
    pub anthropic_version: ApiVersion,
    /// Your unique API key for authentication.
    #[serde(skip)]
    pub x_api_key: Cow<'a, str>,
    /// The body of the request.
    pub body: MessagesRequestBody<'a>,
    #[serde(skip)]
    pub _ne: (),
}

impl Default for MessagesRequest<'_> {
    fn default() -> Self {
        MessagesRequest {
            anthropic_beta: None,
            anthropic_version: ApiVersion::Latest,
            x_api_key: "".into(),
            body: MessagesRequestBody::default(),
            _ne: (),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct MessagesRequestBody<'a> {
    /// The model that will complete your prompt.
    pub model: Model,
    /// Input messages.
    pub messages: Vec<InputMessage>,
    /// The maximum number of tokens to generate before stopping.
    pub max_tokens: u32,
    /// Container identifier for reuse across requests.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container: Option<Cow<'a, str>>,
    /// MCP servers to be utilized in this request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mcp_servers: Option<Vec<McpServer>>,
    /// An object describing metadata about the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata<'a>>,
    /// Determines whether to use priority capacity (if available) or standard capacity for this request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<ServiceTier>,
    /// Custom text sequences that will cause the model to stop generating.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<Cow<'a, str>>>,
    /// Whether to incrementally stream the response using server-sent events.
    pub stream: bool,
    /// System prompt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<Cow<'a, str>>,
    /// Amount of randomness injected into the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    /// Configuration for enabling Claude's extended thinking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<Thinking>,
    /// How the model should use the provided tools.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,
    /// Definitions of tools that the model may use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<Tool<'a>>>,
    /// Only sample from the top K options for each subsequent token.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<u32>,
    /// Use nucleus sampling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip)]
    pub _ne: (),
}

impl Default for MessagesRequestBody<'_> {
    fn default() -> Self {
        MessagesRequestBody {
            model: Model::ClaudeSonnet4_5,
            messages: vec![],
            max_tokens: 2048,
            container: None,
            mcp_servers: None,
            metadata: None,
            service_tier: None,
            stop_sequences: None,
            stream: false,
            system: None,
            temperature: Some(1.0),
            thinking: None,
            tool_choice: None,
            tools: None,
            top_k: None,
            top_p: None,
            _ne: (),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum MessagesResponse {
    Error(ApiError),
    Message(Message),
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct Message {
    /// Unique object identifier.
    pub id: String,
    /// Content generated by the model.
    pub content: Content,
    /// The model that handled the request.
    pub model: Model,
    /// Conversational role of the generated message.
    pub role: Role,
    /// The reason that we stopped.
    pub stop_reason: Option<StopReason>,
    /// Which custom stop sequence was generated, if any.
    pub stop_sequence: Option<String>,
    // TODO: usage
    // TODO: container
    #[serde(skip)]
    _ne: (),
}

impl Default for Message {
    fn default() -> Self {
        Self {
            id: String::new(),
            role: Role::Assistant,
            content: Content::String(String::new()),
            model: Model::ClaudeSonnet3_5,
            stop_reason: None,
            stop_sequence: None,
            _ne: (),
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct MessageDelta {
    /// The reason that we stopped.
    pub stop_reason: Option<StopReason>,
    /// Which custom stop sequence was generated, if any.
    pub stop_sequence: Option<String>,
    #[serde(skip)]
    _ne: (),
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    /// The model reached a natural stopping point
    EndTurn,
    /// We exceeded the requested max_tokens or the model's maximum
    MaxTokens,
    /// One of your provided custom stop_sequences was generated
    StopSequence,
    /// The model invoked one or more tools
    ToolUse,
    /// We paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.
    PauseTurn,
    /// When streaming classifiers intervene to handle potential policy violations
    Refusal,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum MessagesResponseEvent {
    Ping,
    MessageStart {
        message: Message,
    },
    MessageDelta {
        delta: MessageDelta,
    },
    MessageStop,
    ContentBlockStart {
        index: usize,
        content_block: ContentBlock,
    },
    ContentBlockDelta {
        index: usize,
        delta: ContentBlockDelta,
    },
    ContentBlockStop {
        index: usize,
    },
}

#[derive(Debug, Error)]
pub enum AnthropicError {
    #[error("You must set stream to false to use messages")]
    StreamEnabled,
    #[error("You must set stream to true to use messages_stream")]
    StreamNotEnabled,
    #[error(transparent)]
    Reqwest(#[from] reqwest::Error),
    #[error(transparent)]
    Serde(#[from] serde_json::Error),
    #[error(transparent)]
    Api(#[from] ApiError),
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct ApiError {
    pub error: ApiErrorDetails,
    #[serde(skip)]
    _ne: (),
}

impl Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} - {}", self.error.r#type, self.error.message)
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[allow(clippy::manual_non_exhaustive)]
pub struct ApiErrorDetails {
    pub r#type: String,
    pub message: String,
    #[serde(skip)]
    _ne: (),
}

impl std::error::Error for ApiError {}

pub struct MessageStream {
    stream: Pin<Box<dyn futures_core::Stream<Item = reqwest::Result<Bytes>> + Send>>,
    buf: Vec<u8>,
}

impl MessageStream {
    pub async fn recv(&mut self) -> Result<Option<MessagesResponseEvent>, AnthropicError> {
        let mut lines_parsed = 0;
        let mut data = None;
        loop {
            while let Some(at) = self.buf.iter().position(|&b| b == b'\n') {
                let line = self.buf.drain(..=at).collect::<Vec<u8>>();
                let line = String::from_utf8_lossy(&line);
                let line = line.trim();

                match lines_parsed {
                    0 => assert!(line.strip_prefix("event: ").is_some()),
                    1 => data = Some(serde_json::from_str(line.strip_prefix("data: ").unwrap())?),
                    2 => return Ok(data.unwrap()),
                    _ => unreachable!(),
                }

                lines_parsed += 1;
                lines_parsed %= 3;
            }

            match self.stream.next().await {
                Some(Ok(bytes)) => self.buf.extend_from_slice(&bytes),
                Some(Err(err)) => return Err(AnthropicError::Reqwest(err)),
                None => return Ok(None),
            }
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct AnthropicClient {
    client: reqwest::Client,
}

impl AnthropicClient {
    pub fn new() -> Self {
        AnthropicClient {
            client: reqwest::Client::new(),
        }
    }

    /// Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.
    pub async fn messages(&self, request: &MessagesRequest<'_>) -> Result<Message, AnthropicError> {
        if request.body.stream {
            return Err(AnthropicError::StreamEnabled);
        }

        let mut post = self.client.post("https://api.anthropic.com/v1/messages");

        if let Some(beta) = &request.anthropic_beta {
            post = post.header("anthropic-beta", beta.join(","));
        }

        let response = post
            .header("anthropic-version", request.anthropic_version.as_ref())
            .header("x-api-key", request.x_api_key.as_ref())
            .body(serde_json::to_string(&request.body)?)
            .send()
            .await?;

        let message_text = response.text().await?;
        match serde_json::from_str::<MessagesResponse>(&message_text)? {
            MessagesResponse::Message(messages_response) => Ok(messages_response),
            MessagesResponse::Error(api_error) => Err(AnthropicError::Api(api_error)),
        }
    }

    /// Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.
    pub async fn messages_stream(
        &self,
        request: &MessagesRequest<'_>,
    ) -> Result<MessageStream, AnthropicError> {
        if !request.body.stream {
            return Err(AnthropicError::StreamNotEnabled);
        }

        let mut post = self.client.post("https://api.anthropic.com/v1/messages");

        if let Some(beta) = &request.anthropic_beta {
            post = post.header("anthropic-beta", beta.join(","));
        }

        let response = post
            .header("anthropic-version", request.anthropic_version.as_ref())
            .header("x-api-key", request.x_api_key.as_ref())
            .body(serde_json::to_string(&request.body)?)
            .send()
            .await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await?;
            if let Ok(api_error) = serde_json::from_str::<ApiError>(&error_text) {
                return Err(AnthropicError::Api(api_error));
            }

            return Err(AnthropicError::Api(ApiError {
                error: ApiErrorDetails {
                    r#type: format!("http_error_{}", status.as_u16()),
                    message: error_text,
                    ..Default::default()
                },
                ..Default::default()
            }));
        }

        Ok(MessageStream {
            stream: Box::pin(response.bytes_stream()),
            buf: vec![],
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[ignore]
    #[tokio::test]
    async fn test_messages() {
        AnthropicClient::new()
            .messages(&MessagesRequest {
                anthropic_beta: None,
                anthropic_version: ApiVersion::Latest,
                x_api_key: env!("ANTHROPIC_API_KEY").into(),
                body: MessagesRequestBody {
                    model: Model::ClaudeSonnet3_5,
                    messages: vec![InputMessage {
                        role: Role::User,
                        content: Content::String("Hello, how are you?".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                ..Default::default()
            })
            .await
            .unwrap();
    }

    #[ignore]
    #[tokio::test]
    async fn test_messages_stream() {
        tracing_subscriber::fmt::init();

        let mut stream = AnthropicClient::new()
            .messages_stream(&MessagesRequest {
                anthropic_beta: None,
                anthropic_version: ApiVersion::Latest,
                x_api_key: env!("ANTHROPIC_API_KEY").into(),
                body: MessagesRequestBody {
                    model: Model::ClaudeSonnet3_5,
                    messages: vec![InputMessage {
                        role: Role::User,
                        content: Content::String("Hello, how are you?".to_string()),
                        ..Default::default()
                    }],
                    stream: true,
                    ..Default::default()
                },
                ..Default::default()
            })
            .await
            .unwrap();

        while let Some(event) = stream.recv().await.unwrap() {
            println!("{:?}", event);
        }
    }
}