ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::types::{
    Attachment, Content, ContentPart, Effort, Message, ModelSpec, Role, StopReason, ToolDefinition,
    Usage, WebCitation, WebSearchResult, replay_safe_tool_args,
};
use anyhow::Result;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashSet;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct AnthropicMessage {
    pub role: String,
    pub content: AnthropicContent,
}

/// Anthropic content can be either a string or array of content blocks
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub(in crate::anthropic) enum AnthropicContent {
    Text(String),
    Blocks(Vec<ContentBlock>),
}

impl AnthropicContent {
    /// The text blocks joined with newlines, as [`Content::as_text`] joins parts.
    pub(in crate::anthropic) fn as_text(&self) -> String {
        match self {
            Self::Text(text) => text.clone(),
            Self::Blocks(blocks) => blocks
                .iter()
                .filter_map(|block| match block {
                    ContentBlock::Text { text, .. } => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("\n"),
        }
    }
}

/// Individual content blocks for Anthropic messages. A block type this
/// version does not know is kept verbatim as [`ContentBlock::Unknown`], so a
/// response round-trips without loss.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum ContentBlock {
    Text {
        text: String,
        #[serde(skip_serializing_if = "Vec::is_empty")]
        citations: Vec<Citation>,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    Image {
        source: Source,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    Document {
        source: Source,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    ToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    ToolResult {
        tool_use_id: String,
        content: AnthropicContent,
        is_error: bool,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    ServerToolUse {
        id: String,
        name: String,
        input: serde_json::Value,
    },
    WebSearchToolResult {
        tool_use_id: String,
        content: WebSearchContent,
    },
    Thinking {
        thinking: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        signature: Option<String>,
    },
    RedactedThinking {
        data: String,
    },
    /// A block whose `type` this version does not know, kept as received.
    #[serde(untagged)]
    Unknown(serde_json::Value),
}

fn parse_payload<T, E>(payload: serde_json::Value) -> std::result::Result<T, E>
where
    T: serde::de::DeserializeOwned,
    E: serde::de::Error,
{
    serde_json::from_value(payload).map_err(E::custom)
}

/// Hand-written rather than derived: a derive would need an `untagged`
/// fallback for [`ContentBlock::Unknown`], and serde routes a *known* `type`
/// with a malformed body through that fallback too. Here such a block stays a
/// decode error instead of silently becoming an unknown block.
impl<'de> Deserialize<'de> for ContentBlock {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let payload = serde_json::Value::deserialize(deserializer)?;
        match payload.get("type").and_then(serde_json::Value::as_str) {
            Some("text") => {
                #[derive(Deserialize)]
                struct TextBlock {
                    text: String,
                    #[serde(default)]
                    citations: Vec<Citation>,
                    #[serde(default)]
                    cache_control: Option<CacheControl>,
                }
                let block: TextBlock = parse_payload(payload)?;
                Ok(Self::Text {
                    text: block.text,
                    citations: block.citations,
                    cache_control: block.cache_control,
                })
            }
            Some("image") => {
                #[derive(Deserialize)]
                struct ImageBlock {
                    source: Source,
                    #[serde(default)]
                    cache_control: Option<CacheControl>,
                }
                let block: ImageBlock = parse_payload(payload)?;
                Ok(Self::Image { source: block.source, cache_control: block.cache_control })
            }
            Some("document") => {
                #[derive(Deserialize)]
                struct DocumentBlock {
                    source: Source,
                    #[serde(default)]
                    cache_control: Option<CacheControl>,
                }
                let block: DocumentBlock = parse_payload(payload)?;
                Ok(Self::Document { source: block.source, cache_control: block.cache_control })
            }
            Some("tool_use") => {
                #[derive(Deserialize)]
                struct ToolUseBlock {
                    id: String,
                    name: String,
                    input: serde_json::Value,
                    #[serde(default)]
                    cache_control: Option<CacheControl>,
                }
                let block: ToolUseBlock = parse_payload(payload)?;
                Ok(Self::ToolUse {
                    id: block.id,
                    name: block.name,
                    input: block.input,
                    cache_control: block.cache_control,
                })
            }
            Some("tool_result") => {
                #[derive(Deserialize)]
                struct ToolResultBlock {
                    tool_use_id: String,
                    content: AnthropicContent,
                    is_error: bool,
                    #[serde(default)]
                    cache_control: Option<CacheControl>,
                }
                let block: ToolResultBlock = parse_payload(payload)?;
                Ok(Self::ToolResult {
                    tool_use_id: block.tool_use_id,
                    content: block.content,
                    is_error: block.is_error,
                    cache_control: block.cache_control,
                })
            }
            Some("server_tool_use") => {
                #[derive(Deserialize)]
                struct ServerToolUseBlock {
                    id: String,
                    name: String,
                    input: serde_json::Value,
                }
                let block: ServerToolUseBlock = parse_payload(payload)?;
                Ok(Self::ServerToolUse { id: block.id, name: block.name, input: block.input })
            }
            Some("web_search_tool_result") => {
                #[derive(Deserialize)]
                struct WebSearchToolResultBlock {
                    tool_use_id: String,
                    content: WebSearchContent,
                }
                let block: WebSearchToolResultBlock = parse_payload(payload)?;
                Ok(Self::WebSearchToolResult {
                    tool_use_id: block.tool_use_id,
                    content: block.content,
                })
            }
            Some("thinking") => {
                #[derive(Deserialize)]
                struct ThinkingBlock {
                    thinking: String,
                    signature: Option<String>,
                }
                let block: ThinkingBlock = parse_payload(payload)?;
                Ok(Self::Thinking { thinking: block.thinking, signature: block.signature })
            }
            Some("redacted_thinking") => {
                #[derive(Deserialize)]
                struct RedactedThinkingBlock {
                    data: String,
                }
                let block: RedactedThinkingBlock = parse_payload(payload)?;
                Ok(Self::RedactedThinking { data: block.data })
            }
            _ => Ok(Self::Unknown(payload)),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct WebSearchResultContent {
    #[serde(rename = "type")]
    pub result_type: String,
    pub title: String,
    pub url: String,
    #[serde(default)]
    pub encrypted_content: String,
    pub page_age: Option<String>,
}

/// Web search content - can be successful results, an error, or unknown format
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub(in crate::anthropic) enum WebSearchContent {
    Results(Vec<WebSearchResultContent>),
    Error(WebSearchError),
    Unknown(serde_json::Value), // Fallback for any unexpected format
}

/// Web search error when the tool is unavailable
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct WebSearchError {
    #[serde(rename = "type")]
    pub error_type: String,
    pub error_code: String,
}

/// Citation from web search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct Citation {
    #[serde(rename = "type")]
    pub citation_type: String,
    pub url: String,
    pub title: String,
    #[serde(default)]
    pub cited_text: String,
    #[serde(default)]
    pub encrypted_index: String,
}

/// Where an image or document block's content comes from.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub(in crate::anthropic) enum Source {
    #[serde(rename = "url")]
    Url { url: String },
    #[serde(rename = "base64")]
    Base64 { media_type: String, data: String },
}

impl From<&Attachment> for Source {
    fn from(attachment: &Attachment) -> Self {
        match attachment {
            Attachment::Url { url } => Self::Url { url: url.clone() },
            Attachment::Base64 { media_type, data } => {
                Self::Base64 { media_type: media_type.clone(), data: data.clone() }
            }
        }
    }
}

/// Thinking configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum ThinkingConfig {
    Enabled {
        budget_tokens: u32,
        #[serde(skip_serializing_if = "Option::is_none")]
        display: Option<ThinkingDisplay>,
    },
    Disabled,
    BetweenTools,
    Adaptive {
        #[serde(skip_serializing_if = "Option::is_none")]
        display: Option<ThinkingDisplay>,
    },
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(in crate::anthropic) enum ThinkingDisplay {
    Summarized,
    Omitted,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub(in crate::anthropic) enum OutputEffort {
    Low,
    Medium,
    High,
    #[serde(rename = "xhigh")]
    XHigh,
    Max,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::anthropic) struct OutputConfig {
    pub(in crate::anthropic) effort: OutputEffort,
}

/// An ephemeral breakpoint caches the prefix through the marked block.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum CacheControl {
    Ephemeral {
        /// Absent for the default five minutes.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ttl: Option<Ttl>,
    },
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub(in crate::anthropic) enum Ttl {
    #[serde(rename = "1h")]
    Hour,
}

#[derive(Debug, Deserialize)]
pub(in crate::anthropic) struct ListModelsResponse {
    pub data: Vec<AnthropicModel>,
}

#[derive(Debug, Deserialize)]
pub(in crate::anthropic) struct AnthropicModel {
    id: String,
    #[serde(default, alias = "name")]
    display_name: Option<String>,
    #[serde(default)]
    max_input_tokens: Option<u32>,
    #[serde(default)]
    max_tokens: Option<u32>,
    #[serde(default)]
    capabilities: Option<AnthropicModelCapabilities>,
}

#[derive(Debug, Deserialize)]
struct AnthropicModelCapabilities {
    #[serde(default)]
    image_input: Option<CapabilitySupport>,
    #[serde(default)]
    thinking: Option<CapabilitySupport>,
}

#[derive(Debug, Deserialize)]
struct CapabilitySupport {
    supported: bool,
}

impl From<AnthropicModel> for ModelSpec {
    fn from(model: AnthropicModel) -> Self {
        let support_vision = model
            .capabilities
            .as_ref()
            .and_then(|capabilities| capabilities.image_input.as_ref())
            .map(|capability| capability.supported);
        let effort = model
            .capabilities
            .as_ref()
            .and_then(|capabilities| capabilities.thinking.as_ref())
            .and_then(|capability| capability.supported.then_some(Effort::Medium));

        ModelSpec {
            id: model.id,
            display_name: model.display_name,
            max_tokens: model.max_tokens,
            context_limit: model.max_input_tokens,
            effort,
            support_vision,
            ..Default::default()
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub(in crate::anthropic) struct SystemBlock {
    #[serde(rename = "type")]
    pub block_type: String,
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControl>,
}

/// Carries no sampling parameters: on API version `2026-10-21` a request with
/// `temperature`, `top_p` or `top_k` is rejected on every model, so a
/// [`ChatRequest`](crate::types::ChatRequest)'s `temperature` is not sent.
#[derive(Debug, Clone, Default, Serialize)]
pub(in crate::anthropic) struct MessageRequest {
    pub model: String,
    pub max_tokens: u32,
    pub messages: Vec<AnthropicMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<Vec<SystemBlock>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<AnthropicTool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<AnthropicToolChoice>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<ThinkingConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_config: Option<OutputConfig>,
    /// Top-level auto-caching: the API automatically applies the cache breakpoint
    /// to the last cacheable block and moves it forward as conversations grow.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_control: Option<CacheControl>,
}

/// `tool_choice` on the Messages API. Only the constraining forms are ever
/// sent; leaving the field out is the API's `auto`.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum AnthropicToolChoice {
    Any,
    Tool { name: String },
    None,
}

/// Unified tool type for Anthropic API (supports both user tools and server tools)
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub(in crate::anthropic) enum AnthropicTool {
    /// User-defined function tool
    Function {
        #[serde(flatten)]
        definition: ToolDefinition,
        #[serde(skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
        /// Stream the call's input as it is written rather than in one piece
        /// at the end. The server then skips validating it, which a malformed
        /// call already covers.
        #[serde(skip_serializing_if = "std::ops::Not::not")]
        eager_input_streaming: bool,
    },
    /// Server tool like `web_search`
    ServerTool(ServerTool),
}

/// Server tool definition (e.g., `web_search`)
#[derive(Debug, Clone, Serialize)]
pub(in crate::anthropic) struct ServerTool {
    #[serde(rename = "type")]
    pub tool_type: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_uses: Option<u32>,
}

/// A complete Messages API response: what web search reads. Chat responses
/// arrive as a stream and are never decoded in this shape.
#[derive(Debug, Deserialize)]
pub(in crate::anthropic) struct MessageResponse {
    pub content: Vec<ContentBlock>,
    pub stop_reason: Option<String>,
}

/// Usage as Anthropic streams it, in pieces: `message_start` carries the
/// input and cache counts, each `message_delta` the running output count.
#[derive(Debug, Clone, Copy, Default, Deserialize)]
pub(in crate::anthropic) struct AnthropicUsageDelta {
    pub input_tokens: Option<u32>,
    pub output_tokens: Option<u32>,
    pub cache_creation_input_tokens: Option<u32>,
    pub cache_read_input_tokens: Option<u32>,
}

impl AnthropicUsageDelta {
    /// Fold a later event's counts over these; a count the event omits keeps
    /// its earlier value.
    pub(in crate::anthropic) fn patch(&mut self, later: AnthropicUsageDelta) {
        self.input_tokens = later.input_tokens.or(self.input_tokens);
        self.output_tokens = later.output_tokens.or(self.output_tokens);
        self.cache_creation_input_tokens =
            later.cache_creation_input_tokens.or(self.cache_creation_input_tokens);
        self.cache_read_input_tokens =
            later.cache_read_input_tokens.or(self.cache_read_input_tokens);
    }
}

/// Anthropic reports `input_tokens` as the uncached part only; the cache
/// counts are added back for the true total.
impl From<AnthropicUsageDelta> for Usage {
    fn from(usage: AnthropicUsageDelta) -> Self {
        let cache_write_tokens = usage.cache_creation_input_tokens;
        let cache_read_tokens = usage.cache_read_input_tokens;
        Usage {
            input_tokens: usage
                .input_tokens
                .unwrap_or_default()
                .saturating_add(cache_write_tokens.unwrap_or_default())
                .saturating_add(cache_read_tokens.unwrap_or_default()),
            output_tokens: usage.output_tokens.unwrap_or_default(),
            cache_read_tokens,
            cache_write_tokens,
        }
    }
}

/// Minimal `message_start.message` shape needed for stream accumulation.
#[derive(Debug, Clone, Deserialize)]
pub(in crate::anthropic) struct AnthropicStreamMessage {
    #[serde(default)]
    pub usage: AnthropicUsageDelta,
}

#[derive(Debug, Clone)]
pub(in crate::anthropic) enum AnthropicStreamEvent {
    MessageStart { message: AnthropicStreamMessage },
    ContentBlockStart { index: u32, content_block: ContentBlock },
    ContentBlockDelta { index: u32, delta: AnthropicDelta },
    ContentBlockStop { index: u32 },
    MessageDelta { delta: AnthropicMessageDelta, usage: AnthropicUsageDelta },
    MessageStop,
    Ping,
    Error { error: AnthropicError },

    Unknown { event_type: Option<String>, payload: serde_json::Value },
}

impl<'de> Deserialize<'de> for AnthropicStreamEvent {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let payload = serde_json::Value::deserialize(deserializer)?;
        let event_type =
            payload.get("type").and_then(serde_json::Value::as_str).map(str::to_string);

        match event_type.as_deref() {
            Some("message_start") => {
                #[derive(Deserialize)]
                struct MessageStartEvent {
                    message: AnthropicStreamMessage,
                }
                let event: MessageStartEvent = parse_payload(payload)?;
                Ok(Self::MessageStart { message: event.message })
            }
            Some("content_block_start") => {
                #[derive(Deserialize)]
                struct ContentBlockStartEvent {
                    index: u32,
                    content_block: ContentBlock,
                }
                let event: ContentBlockStartEvent = parse_payload(payload)?;
                Ok(Self::ContentBlockStart {
                    index: event.index,
                    content_block: event.content_block,
                })
            }
            Some("content_block_delta") => {
                #[derive(Deserialize)]
                struct ContentBlockDeltaEvent {
                    index: u32,
                    delta: AnthropicDelta,
                }
                let event: ContentBlockDeltaEvent = parse_payload(payload)?;
                Ok(Self::ContentBlockDelta { index: event.index, delta: event.delta })
            }
            Some("content_block_stop") => {
                #[derive(Deserialize)]
                struct ContentBlockStopEvent {
                    index: u32,
                }
                let event: ContentBlockStopEvent = parse_payload(payload)?;
                Ok(Self::ContentBlockStop { index: event.index })
            }
            Some("message_delta") => {
                #[derive(Deserialize)]
                struct MessageDeltaEvent {
                    delta: AnthropicMessageDelta,
                    #[serde(default)]
                    usage: AnthropicUsageDelta,
                }
                let event: MessageDeltaEvent = parse_payload(payload)?;
                Ok(Self::MessageDelta { delta: event.delta, usage: event.usage })
            }
            Some("message_stop") => Ok(Self::MessageStop),
            Some("ping") => Ok(Self::Ping),
            Some("error") => {
                #[derive(Deserialize)]
                struct ErrorEvent {
                    error: AnthropicError,
                }
                let event: ErrorEvent = parse_payload(payload)?;
                Ok(Self::Error { error: event.error })
            }
            _ => Ok(Self::Unknown { event_type, payload }),
        }
    }
}

/// Error information from streaming events
#[derive(Debug, Clone, Deserialize)]
pub(in crate::anthropic) struct AnthropicError {
    #[serde(rename = "type")]
    pub error_type: String,
    pub message: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::anthropic) enum AnthropicDelta {
    TextDelta {
        text: String,
    },
    InputJsonDelta {
        partial_json: String,
    },
    ThinkingDelta {
        thinking: String,
    },
    SignatureDelta {
        signature: String,
    },
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Clone, Deserialize)]
pub(in crate::anthropic) struct AnthropicMessageDelta {
    pub stop_reason: Option<String>,
}

impl TryFrom<&Content> for AnthropicContent {
    type Error = anyhow::Error;
    fn try_from(content: &Content) -> Result<Self> {
        match content {
            Content::Text(text) => Ok(AnthropicContent::Text(text.clone())),
            Content::Parts(parts) => Ok(AnthropicContent::Blocks(
                parts
                    .iter()
                    // Anthropic rejects an unsigned thinking block (can happen when a
                    // turn is cut mid-thinking); drop it rather than send it.
                    .filter(|p| !matches!(p, ContentPart::Thinking { signature: None, .. }))
                    .map(ContentBlock::try_from)
                    .collect::<Result<Vec<_>>>()?,
            )),
        }
    }
}
impl TryFrom<&ContentPart> for ContentBlock {
    type Error = anyhow::Error;
    fn try_from(content: &ContentPart) -> Result<Self> {
        match content {
            ContentPart::Text(text) => Ok(ContentBlock::Text {
                text: text.clone(),
                citations: vec![],
                cache_control: None,
            }),
            ContentPart::Image(image) => {
                Ok(ContentBlock::Image { source: image.into(), cache_control: None })
            }
            ContentPart::Document(document) => {
                Ok(ContentBlock::Document { source: document.into(), cache_control: None })
            }
            ContentPart::Thinking { text, signature } => {
                Ok(ContentBlock::Thinking { thinking: text.clone(), signature: signature.clone() })
            }
            ContentPart::RedactedThinking { data } => {
                Ok(ContentBlock::RedactedThinking { data: data.clone() })
            }
            ContentPart::ToolUse(tool_use) => Ok(ContentBlock::ToolUse {
                id: wire_tool_id(&tool_use.id),
                name: tool_use.name.clone(),
                input: replay_safe_tool_args(tool_use).into_owned(),
                cache_control: None,
            }),
            ContentPart::ToolResult(tool_result) => Ok(ContentBlock::ToolResult {
                tool_use_id: wire_tool_id(&tool_result.tool_use_id),
                content: AnthropicContent::try_from(&tool_result.content)?,
                is_error: tool_result.is_error,
                cache_control: None,
            }),
        }
    }
}

/// A tool-call id in the form Anthropic accepts (`^[a-zA-Z0-9_-]+$`). Calls
/// another provider made (Kimi's `functions.Read:0`) replay after a switch.
/// A valid id passes through; any other is cleaned and suffixed with a hash
/// of the original, so distinct ids stay distinct (`call:0` never meets a
/// native `call_0`) and call and result map alike.
fn wire_tool_id(id: &str) -> String {
    use sha2::{Digest, Sha256};

    let valid = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
    if !id.is_empty() && id.chars().all(valid) {
        return id.to_string();
    }
    let cleaned: String = id.chars().map(|c| if valid(c) { c } else { '_' }).collect();
    let digest = Sha256::digest(id.as_bytes());
    let hash: String = digest[..4].iter().map(|byte| format!("{byte:02x}")).collect();
    format!("{cleaned}_{hash}")
}

impl AnthropicMessage {
    /// No content after conversion — e.g. an unsigned-thinking-only turn that was stripped.
    pub(in crate::anthropic) fn is_content_empty(&self) -> bool {
        matches!(&self.content, AnthropicContent::Blocks(blocks) if blocks.is_empty())
    }
}

impl TryFrom<&Message> for AnthropicMessage {
    type Error = anyhow::Error;

    fn try_from(message: &Message) -> Result<Self> {
        Ok(AnthropicMessage {
            role: match &message.role {
                Role::User => "user".to_string(),
                Role::Model => "assistant".to_string(),
                Role::System => "system".to_string(),
                Role::Custom(role) => role.clone(),
            },
            content: AnthropicContent::try_from(&message.content)?,
        })
    }
}

impl TryFrom<MessageResponse> for WebSearchResult {
    type Error = anyhow::Error;

    fn try_from(response: MessageResponse) -> Result<Self> {
        let mut text_parts: Vec<String> = Vec::new();
        let mut citations: Vec<WebCitation> = Vec::new();
        let mut seen_urls: HashSet<String> = HashSet::new();

        for block in response.content {
            match block {
                ContentBlock::Text { text, citations: block_citations, .. } => {
                    if !text.is_empty() {
                        text_parts.push(text);
                    }
                    for citation in block_citations {
                        if seen_urls.insert(citation.url.clone()) {
                            citations
                                .push(WebCitation { title: citation.title, uri: citation.url });
                        }
                    }
                }
                ContentBlock::WebSearchToolResult { content, .. } => match content {
                    WebSearchContent::Results(results) => {
                        for result in results {
                            if seen_urls.insert(result.url.clone()) {
                                citations
                                    .push(WebCitation { title: result.title, uri: result.url });
                            }
                        }
                    }
                    WebSearchContent::Error(error) => {
                        anyhow::bail!(
                            "Web search failed: {} ({})",
                            error.error_code,
                            error.error_type
                        );
                    }
                    WebSearchContent::Unknown(value) => {
                        anyhow::bail!(
                            "Web search returned unexpected format: {}",
                            serde_json::to_string(&value).unwrap_or_default()
                        );
                    }
                },
                _ => {}
            }
        }

        let content = Content::Text(text_parts.join("\n"));
        Ok(WebSearchResult { content, citations })
    }
}

pub(in crate::anthropic) fn stop_reason(value: &str) -> StopReason {
    match value {
        "end_turn" => StopReason::EndTurn,
        "max_tokens" => StopReason::MaxTokens,
        "refusal" => StopReason::Refusal,
        other => StopReason::Other(other.to_string()),
    }
}