rust_llm 2.0.0

A 1:1 Rust port of RubyLLM 2.0: one API for chat, tools, agents, and embeddings across providers.
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
//! Port of `message.rb`, `chunk.rb`, `tool_call.rb`, `thinking.rb`, `citation.rb`,
//! `server_tool_call.rb`, and the usage `Entry` from `accounting/usage.rb`.

use indexmap_lite::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::attachment::Attachment;
use crate::cost::{Cost, Tier};
use crate::error::{Error, Result};
use crate::model::Model;
use crate::tokens::Tokens;

/// Insertion-ordered map keyed by tool call id, like the Ruby Hash RubyLLM uses.
pub mod indexmap_lite {
    #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
    pub struct IndexMap<V>(pub Vec<(String, V)>);

    impl<V> Default for IndexMap<V> {
        fn default() -> Self {
            IndexMap(Vec::new())
        }
    }

    impl<V> IndexMap<V> {
        pub fn new() -> Self {
            IndexMap(Vec::new())
        }
        pub fn get(&self, key: &str) -> Option<&V> {
            self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
        }
        pub fn get_mut(&mut self, key: &str) -> Option<&mut V> {
            self.0.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v)
        }
        pub fn insert(&mut self, key: String, value: V) {
            match self.get_mut(&key) {
                Some(slot) => *slot = value,
                None => self.0.push((key, value)),
            }
        }
        pub fn contains_key(&self, key: &str) -> bool {
            self.get(key).is_some()
        }
        pub fn values(&self) -> impl Iterator<Item = &V> {
            self.0.iter().map(|(_, v)| v)
        }
        pub fn keys(&self) -> impl Iterator<Item = &String> {
            self.0.iter().map(|(k, _)| k)
        }
        pub fn iter(&self) -> impl Iterator<Item = (&String, &V)> {
            self.0.iter().map(|(k, v)| (k, v))
        }
        pub fn len(&self) -> usize {
            self.0.len()
        }
        pub fn is_empty(&self) -> bool {
            self.0.is_empty()
        }
    }

    impl<V> FromIterator<(String, V)> for IndexMap<V> {
        fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
            let mut map = IndexMap::new();
            for (k, v) in iter {
                map.insert(k, v);
            }
            map
        }
    }
}

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

impl Role {
    pub fn as_str(&self) -> &'static str {
        match self {
            Role::System => "system",
            Role::User => "user",
            Role::Assistant => "assistant",
            Role::Tool => "tool",
        }
    }

    pub fn parse(s: &str) -> Result<Role> {
        match s {
            "system" => Ok(Role::System),
            "user" => Ok(Role::User),
            "assistant" => Ok(Role::Assistant),
            "tool" => Ok(Role::Tool),
            _ => Err(Error::Argument(
                "Expected role to be one of: system, user, assistant, tool".into(),
            )),
        }
    }
}

/// Normalized finish reasons (`FINISH_REASONS` in each protocol). Unknown reasons are kept verbatim.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FinishReason {
    Stop,
    MaxTokens,
    ToolCalls,
    ContentFilter,
    PauseTurn,
    Other(String),
}

impl FinishReason {
    pub fn from_symbol(s: &str) -> FinishReason {
        match s {
            "stop" => FinishReason::Stop,
            "max_tokens" => FinishReason::MaxTokens,
            "tool_calls" => FinishReason::ToolCalls,
            "content_filter" => FinishReason::ContentFilter,
            "pause_turn" => FinishReason::PauseTurn,
            other => FinishReason::Other(other.to_string()),
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            FinishReason::Stop => "stop",
            FinishReason::MaxTokens => "max_tokens",
            FinishReason::ToolCalls => "tool_calls",
            FinishReason::ContentFilter => "content_filter",
            FinishReason::PauseTurn => "pause_turn",
            FinishReason::Other(s) => s,
        }
    }
}

/// Model deliberation (`Thinking`). The signature is opaque provider state that must be replayed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Thinking {
    pub text: Option<String>,
    pub signature: Option<String>,
}

impl Thinking {
    /// `Thinking.build`: `None` when there is neither text nor a signature.
    pub fn build(text: Option<String>, signature: Option<String>) -> Option<Thinking> {
        let signature = signature.filter(|s| !s.is_empty());
        let text = text.filter(|t| !(t.is_empty() && signature.is_none()));
        if text.is_none() && signature.is_none() {
            return None;
        }
        Some(Thinking { text, signature })
    }
}

/// Arguments the model passed to a tool. While streaming they arrive as a JSON string in pieces.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolArguments {
    Parsed(Map<String, Value>),
    Partial(String),
}

impl Default for ToolArguments {
    fn default() -> Self {
        ToolArguments::Parsed(Map::new())
    }
}

impl ToolArguments {
    pub fn as_map(&self) -> Map<String, Value> {
        match self {
            ToolArguments::Parsed(m) => m.clone(),
            ToolArguments::Partial(s) => serde_json::from_str(s).unwrap_or_default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: ToolArguments,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thought_signature: Option<String>,
    #[serde(default)]
    pub remote: bool,
    /// Streaming only: whether this piece carried an id field at all. RubyLLM starts a new call
    /// for any non-nil id (an empty one gets a UUID) and treats a nil id as an argument fragment.
    #[serde(skip)]
    pub(crate) starts: bool,
}

impl ToolCall {
    pub fn new(
        id: impl Into<String>,
        name: impl Into<String>,
        arguments: Map<String, Value>,
    ) -> Self {
        ToolCall {
            id: id.into(),
            name: name.into(),
            arguments: ToolArguments::Parsed(arguments),
            thought_signature: None,
            remote: false,
            starts: true,
        }
    }

    /// A streamed piece that opens a call (`id` present, possibly empty): Ruby's
    /// `ToolCall.new(id: '', name:, arguments: '')` as a stream chunk carries it.
    pub fn opening(id: String, name: String, arguments: String) -> ToolCall {
        ToolCall {
            id,
            name,
            arguments: ToolArguments::Partial(arguments),
            thought_signature: None,
            remote: false,
            starts: true,
        }
    }

    /// A streamed argument fragment for a call opened earlier: Ruby's
    /// `ToolCall.new(id: nil, name: nil, arguments: '...')`. A `nil` fragment is an empty one.
    pub fn fragment(arguments: String) -> ToolCall {
        ToolCall {
            id: String::new(),
            name: String::new(),
            arguments: ToolArguments::Partial(arguments),
            thought_signature: None,
            remote: false,
            starts: false,
        }
    }

    pub(crate) fn starts_call(&self) -> bool {
        self.starts
    }

    pub fn arguments(&self) -> Map<String, Value> {
        self.arguments.as_map()
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Citation {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cited_text: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_index: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_index: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_index: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_page: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_page: Option<i64>,
}

/// A tool the provider ran itself (web search, code execution, ...).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServerToolCall {
    #[serde(rename = "type")]
    pub kind: String,
    pub name: Option<String>,
    pub id: Option<String>,
    pub input: Option<Value>,
    pub result: Option<Value>,
    pub raw: Value,
}

/// The raw HTTP exchange behind a response (`message.raw`). Like Faraday's `env.request_body`,
/// the request is kept as the exact serialized text that was sent: every message of a long chat
/// keeps its request, and each request holds the whole conversation so far, so a JSON tree per
/// message cost ~20x the memory. Parse it on demand with `request_body_json`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RawResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Value,
    pub request_body: std::sync::Arc<str>,
}

impl RawResponse {
    /// The request as JSON (`Null` when there was no JSON body, e.g. a GET or multipart upload).
    pub fn request_body_json(&self) -> Value {
        serde_json::from_str(&self.request_body).unwrap_or(Value::Null)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Operation {
    Chat,
    Embedding,
    Moderation,
    Image,
    Speech,
    Transcription,
    Ocr,
    Rerank,
    Judgment,
}

impl Operation {
    pub fn as_str(&self) -> &'static str {
        match self {
            Operation::Chat => "chat",
            Operation::Embedding => "embedding",
            Operation::Moderation => "moderation",
            Operation::Image => "image",
            Operation::Speech => "speech",
            Operation::Transcription => "transcription",
            Operation::Ocr => "ocr",
            Operation::Rerank => "rerank",
            Operation::Judgment => "judgment",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UsageStatus {
    Pending,
    Succeeded,
    Failed,
    Cancelled,
}

impl UsageStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            UsageStatus::Pending => "pending",
            UsageStatus::Succeeded => "succeeded",
            UsageStatus::Failed => "failed",
            UsageStatus::Cancelled => "cancelled",
        }
    }
}

/// `Accounting::Usage::Entry`: one billed attempt. Retries and fallbacks each get their own.
/// `id` gives each attempt the identity Ruby gets from object identity, so persistence links the
/// exact entry even when two attempts carry identical numbers.
#[derive(Debug, Clone, PartialEq)]
pub struct UsageEntry {
    pub id: u64,
    pub operation: Operation,
    pub provider: String,
    pub model: String,
    pub status: UsageStatus,
    pub tokens: Tokens,
    pub cost: Cost,
}

static NEXT_USAGE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

impl UsageEntry {
    /// A fresh process-unique id for a new entry.
    pub fn next_id() -> u64 {
        NEXT_USAGE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    }

    pub fn cost_available(&self) -> bool {
        self.cost.total().is_some()
    }
}

/// One message in a conversation (`RubyLLM::Message`). Streamed pieces use the same type
/// (`Chunk < Message`).
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
    pub role: Role,
    pub content: Option<String>,
    pub attachments: Vec<Attachment>,
    pub model: Option<String>,
    pub tool_calls: Option<IndexMap<ToolCall>>,
    pub tool_call_id: Option<String>,
    pub tokens: Tokens,
    pub thinking: Option<Thinking>,
    pub citations: Vec<Citation>,
    pub server_tool_calls: Vec<ServerToolCall>,
    pub raw_content: Option<Value>,
    pub raw_reasoning: Option<Value>,
    pub finish_reason: Option<FinishReason>,
    pub raw: Option<RawResponse>,
    pub cache_until_here: bool,
    pub usage_entries: Vec<UsageEntry>,
    /// Primary key of the row this message is stored as, set by a persistence layer
    /// (`rust_llm_loco`). `None` means not yet persisted.
    pub record_id: Option<i64>,
    pub(crate) model_info: Option<Model>,
    /// `@supplied_cost`: an explicit `cost:` the message was built with (see [`Message::with_cost`]).
    pub(crate) supplied_cost: Option<Cost>,
}

pub type Chunk = Message;

impl Message {
    pub fn new(role: Role, content: impl Into<Option<String>>) -> Message {
        Message {
            role,
            content: content.into(),
            attachments: Vec::new(),
            model: None,
            tool_calls: None,
            tool_call_id: None,
            tokens: Tokens::default(),
            thinking: None,
            citations: Vec::new(),
            server_tool_calls: Vec::new(),
            raw_content: None,
            raw_reasoning: None,
            finish_reason: None,
            raw: None,
            cache_until_here: false,
            usage_entries: Vec::new(),
            record_id: None,
            model_info: None,
            supplied_cost: None,
        }
    }

    pub fn system(content: impl Into<String>) -> Message {
        Message::new(Role::System, Some(content.into()))
    }

    pub fn user(content: impl Into<String>) -> Message {
        Message::new(Role::User, Some(content.into()))
    }

    pub fn assistant(content: impl Into<String>) -> Message {
        Message::new(Role::Assistant, Some(content.into()))
    }

    pub fn tool_result(tool_call_id: impl Into<String>, content: impl Into<String>) -> Message {
        let mut m = Message::new(Role::Tool, Some(content.into()));
        m.tool_call_id = Some(tool_call_id.into());
        m
    }

    pub(crate) fn chunk() -> Message {
        Message::new(Role::Assistant, None)
    }

    /// `normalize_content`: an assistant turn that only calls tools has content `""`.
    pub(crate) fn normalized(mut self) -> Message {
        if self.role == Role::Assistant && self.content.is_none() && self.is_tool_call() {
            self.content = Some(String::new());
        }
        self
    }

    pub fn with_attachments(mut self, attachments: Vec<Attachment>) -> Message {
        self.attachments = attachments;
        self
    }

    pub fn content(&self) -> &str {
        self.content.as_deref().unwrap_or("")
    }

    /// `Message#parsed`: the content as JSON, for structured output.
    pub fn parsed(&self) -> Result<Option<Value>> {
        match self.content.as_deref() {
            None | Some("") => Ok(None),
            Some(s) => Ok(Some(serde_json::from_str(s)?)),
        }
    }

    pub fn is_tool_call(&self) -> bool {
        self.tool_calls.as_ref().is_some_and(|t| !t.is_empty())
    }

    pub fn is_tool_result(&self) -> bool {
        self.tool_call_id.as_ref().is_some_and(|id| !id.is_empty())
    }

    pub fn is_stopped(&self) -> bool {
        self.finish_reason == Some(FinishReason::Stop) && !self.is_tool_call()
    }

    pub fn is_max_tokens(&self) -> bool {
        self.finish_reason == Some(FinishReason::MaxTokens)
    }

    pub fn is_tool_call_stop(&self) -> bool {
        self.finish_reason == Some(FinishReason::ToolCalls)
            || (self.is_tool_call() && self.finish_reason == Some(FinishReason::Stop))
    }

    pub fn is_content_filtered(&self) -> bool {
        self.finish_reason == Some(FinishReason::ContentFilter)
    }

    /// `Message#tokens`: the usage ledger when present, otherwise what the message was built with.
    pub fn tokens(&self) -> Tokens {
        if self.usage_entries.is_empty() {
            self.tokens.clone()
        } else {
            Tokens::aggregate(self.usage_entries.iter().map(|e| &e.tokens))
        }
    }

    /// `Message#cost`: the recorded attempt costs, else an explicitly supplied `cost:`, else
    /// pricing from `model_info`. Pass a model to price against it instead.
    pub fn cost(&self, model: Option<&Model>) -> Cost {
        if model.is_none() && !self.usage_entries.is_empty() {
            let complete = self.usage_entries.iter().all(UsageEntry::cost_available);
            return Cost::aggregate(self.usage_entries.iter().map(|e| &e.cost), complete);
        }
        if let (None, Some(supplied)) = (model, &self.supplied_cost) {
            return supplied.clone();
        }
        let info = model.cloned().or_else(|| self.model_info());
        Cost::new(&self.tokens(), info.as_ref(), Tier::Standard)
    }

    /// Registry entry of the model that produced this message, if known.
    pub fn model_info(&self) -> Option<Model> {
        if let Some(m) = &self.model_info {
            return Some(m.clone());
        }
        let registry = crate::models::models();
        let entry = self
            .usage_entries
            .iter()
            .rev()
            .find(|e| e.status == UsageStatus::Succeeded);
        match entry {
            Some(e) => registry.find(&e.model, Some(&e.provider)).ok(),
            None => self
                .model
                .as_deref()
                .and_then(|m| registry.find(m, None).ok()),
        }
    }

    /// `Message#without_thinking`: what gets replayed to a provider that did not produce the thinking.
    /// The per-request view of a stored message: everything a protocol renders, without the
    /// bookkeeping it never reads (the HTTP exchange, usage ledger, registry entry). Cloning
    /// those for every message on every request made long chats quadratic.
    pub(crate) fn for_request(&self) -> Message {
        Message {
            role: self.role,
            content: self.content.clone(),
            attachments: self.attachments.clone(),
            model: self.model.clone(),
            tool_calls: self.tool_calls.clone(),
            tool_call_id: self.tool_call_id.clone(),
            tokens: Tokens::default(),
            thinking: self.thinking.clone(),
            citations: self.citations.clone(),
            server_tool_calls: self.server_tool_calls.clone(),
            raw_content: self.raw_content.clone(),
            raw_reasoning: self.raw_reasoning.clone(),
            finish_reason: self.finish_reason.clone(),
            raw: None,
            cache_until_here: self.cache_until_here,
            usage_entries: Vec::new(),
            record_id: self.record_id,
            model_info: None,
            supplied_cost: None,
        }
    }

    pub(crate) fn without_thinking(&self) -> Message {
        let mut m = self.clone();
        m.thinking = None;
        m.raw_reasoning = None;
        if let Some(calls) = &mut m.tool_calls {
            for (_, call) in calls.0.iter_mut() {
                call.thought_signature = None;
            }
        }
        m
    }

    /// `Message.new(cost:)`: an explicitly supplied cost, kept through `to_h`/`from_h`.
    /// Recorded attempt costs still win over it, and an explicit model reprices.
    pub fn with_cost(mut self, cost: Cost) -> Message {
        self.supplied_cost = Some(cost);
        self
    }

    /// `Message#tool_results`: the tool result messages in `conversation` answering this
    /// message's tool calls, or none when it made no calls. Ruby reads the chat through the
    /// message's `conversation` back-link; pass the chat's messages (`chat.messages()`).
    pub fn tool_results<'a>(&self, conversation: &'a [Message]) -> Vec<&'a Message> {
        let Some(calls) = self.tool_calls.as_ref().filter(|c| !c.is_empty()) else {
            return Vec::new();
        };
        conversation
            .iter()
            .filter(|m| {
                m.is_tool_result()
                    && m.tool_call_id
                        .as_deref()
                        .is_some_and(|id| calls.contains_key(id))
            })
            .collect()
    }

    /// `Message.new(message.to_h)`: rebuilds a message from its `to_h` attributes (string keys,
    /// as after a JSON round-trip). Tool calls, thinking, citations, server tool calls, and the
    /// supplied cost come back as value objects. Attachments are rebuilt from their `source`.
    pub fn from_h(h: &Value) -> Result<Message> {
        let str_of = |key: &str| h.get(key).and_then(Value::as_str).map(str::to_string);
        let int_of = |key: &str| h.get(key).and_then(Value::as_i64);
        let role = Role::parse(h.get("role").and_then(Value::as_str).unwrap_or_default())?;
        let mut m = Message::new(role, str_of("content"));
        m.model = str_of("model");
        m.tool_call_id = str_of("tool_call_id");
        if let Some(calls) = h.get("tool_calls").and_then(Value::as_object) {
            m.tool_calls = Some(
                calls
                    .iter()
                    .map(|(id, call)| {
                        let mut tc = ToolCall::new(
                            call.get("id")
                                .and_then(Value::as_str)
                                .unwrap_or(id.as_str()),
                            call.get("name").and_then(Value::as_str).unwrap_or_default(),
                            call.get("arguments")
                                .and_then(Value::as_object)
                                .cloned()
                                .unwrap_or_default(),
                        );
                        tc.thought_signature = call
                            .get("thought_signature")
                            .and_then(Value::as_str)
                            .map(str::to_string);
                        tc.remote = call.get("remote").and_then(Value::as_bool).unwrap_or(false);
                        (id.clone(), tc)
                    })
                    .collect(),
            );
        }
        m.thinking = match h.get("thinking") {
            Some(Value::Object(t)) => Thinking::build(
                t.get("text").and_then(Value::as_str).map(str::to_string),
                t.get("signature")
                    .and_then(Value::as_str)
                    .map(str::to_string),
            ),
            Some(Value::String(text)) => {
                Thinking::build(Some(text.clone()), str_of("thinking_signature"))
            }
            _ => None,
        };
        if let Some(citations) = h.get("citations") {
            m.citations = serde_json::from_value(citations.clone())?;
        }
        for call in h
            .get("server_tool_calls")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            m.server_tool_calls.push(ServerToolCall {
                kind: call
                    .get("type")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string(),
                name: call.get("name").and_then(Value::as_str).map(str::to_string),
                id: call.get("id").and_then(Value::as_str).map(str::to_string),
                input: call.get("input").cloned(),
                result: call.get("result").cloned(),
                raw: call.get("raw").cloned().unwrap_or(Value::Null),
            });
        }
        for a in h
            .get("attachments")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            let source = a
                .as_str()
                .or_else(|| a.get("source").and_then(Value::as_str));
            let source = source
                .ok_or_else(|| Error::Argument(format!("Cannot rebuild an attachment from {a}")))?;
            m.attachments.push(Attachment::new(source));
        }
        m.raw_content = h.get("raw_content").cloned();
        m.raw_reasoning = h.get("raw_reasoning").cloned();
        m.finish_reason = h
            .get("finish_reason")
            .and_then(Value::as_str)
            .map(FinishReason::from_symbol);
        m.cache_until_here = h
            .get("cache_until_here")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        m.supplied_cost = h.get("cost").map(|c| Cost::from_h(c, None));
        m.tokens = Tokens {
            input: int_of("input_tokens"),
            output: int_of("output_tokens"),
            cache_read: int_of("cache_read_tokens"),
            cache_write: int_of("cache_write_tokens"),
            thinking: int_of("thinking_tokens"),
            server_tool_use: h.get("server_tool_use").and_then(Value::as_object).cloned(),
            reported_cost: h.get("reported_cost").and_then(Value::as_f64),
        };
        Ok(m.normalized())
    }

    /// `Message#to_h`: `nil` values and empty attachment, citation, and server tool call lists
    /// are omitted; `cost` appears only when one was supplied.
    pub fn to_h(&self) -> Value {
        let mut h = Map::new();
        h.insert("role".into(), self.role.as_str().into());
        if let Some(c) = &self.content {
            h.insert("content".into(), c.clone().into());
        }
        if !self.attachments.is_empty() {
            h.insert(
                "attachments".into(),
                self.attachments.iter().map(attachment_h).collect(),
            );
        }
        if let Some(m) = &self.model {
            h.insert("model".into(), m.clone().into());
        }
        if self.supplied_cost.is_some() {
            h.insert(
                "cost".into(),
                crate::instrumentation::cost_h(&self.cost(None)),
            );
        }
        if let Some(calls) = &self.tool_calls {
            let calls: Map<String, Value> = calls
                .iter()
                .map(|(k, v)| (k.clone(), tool_call_h(v)))
                .collect();
            h.insert("tool_calls".into(), calls.into());
        }
        if let Some(id) = &self.tool_call_id {
            h.insert("tool_call_id".into(), id.clone().into());
        }
        if let Some(t) = &self.thinking {
            if let Some(text) = &t.text {
                h.insert("thinking".into(), text.clone().into());
            }
            if let Some(sig) = &t.signature {
                h.insert("thinking_signature".into(), sig.clone().into());
            }
        }
        if !self.citations.is_empty() {
            h.insert(
                "citations".into(),
                serde_json::to_value(&self.citations).unwrap(),
            ); // Citation always serializes
        }
        if !self.server_tool_calls.is_empty() {
            h.insert(
                "server_tool_calls".into(),
                self.server_tool_calls
                    .iter()
                    .map(server_tool_call_h)
                    .collect(),
            );
        }
        if let Some(raw) = &self.raw_content {
            h.insert("raw_content".into(), raw.clone());
        }
        if let Some(raw) = &self.raw_reasoning {
            h.insert("raw_reasoning".into(), raw.clone());
        }
        if let Some(r) = &self.finish_reason {
            h.insert("finish_reason".into(), r.as_str().into());
        }
        if self.cache_until_here {
            h.insert("cache_until_here".into(), true.into());
        }
        let t = self.tokens();
        for (k, v) in [
            ("input_tokens", t.input),
            ("output_tokens", t.output),
            ("cache_read_tokens", t.cache_read),
            ("cache_write_tokens", t.cache_write),
            ("thinking_tokens", t.thinking),
        ] {
            if let Some(v) = v {
                h.insert(k.into(), v.into());
            }
        }
        if let Some(s) = &t.server_tool_use {
            h.insert("server_tool_use".into(), Value::Object(s.clone()));
        }
        Value::Object(h)
    }
}

/// `ToolCall#to_h`: `remote` only when true, `thought_signature` only when present.
fn tool_call_h(call: &ToolCall) -> Value {
    let mut h = Map::new();
    h.insert("id".into(), call.id.clone().into());
    h.insert("name".into(), call.name.clone().into());
    h.insert("arguments".into(), Value::Object(call.arguments()));
    if call.remote {
        h.insert("remote".into(), true.into());
    }
    if let Some(sig) = &call.thought_signature {
        h.insert("thought_signature".into(), sig.clone().into());
    }
    Value::Object(h)
}

/// `ServerToolCall#to_h`, omitting `nil` values.
fn server_tool_call_h(call: &ServerToolCall) -> Value {
    let mut h = Map::new();
    h.insert("type".into(), call.kind.clone().into());
    for (key, value) in [
        ("name", call.name.clone().map(Value::from)),
        ("id", call.id.clone().map(Value::from)),
        ("input", call.input.clone()),
        ("result", call.result.clone()),
        ("raw", Some(call.raw.clone()).filter(|r| !r.is_null())),
    ] {
        if let Some(v) = value {
            h.insert(key.into(), v);
        }
    }
    Value::Object(h)
}

/// `Attachment#to_h`: `{ type:, source: }`. In-memory bytes have no source to record (`null`).
fn attachment_h(a: &Attachment) -> Value {
    use crate::attachment::{AttachmentType, Source};
    let kind = match a.kind() {
        AttachmentType::Image => "image",
        AttachmentType::Video => "video",
        AttachmentType::Audio => "audio",
        AttachmentType::Pdf => "pdf",
        AttachmentType::Text => "text",
        AttachmentType::Document => "document",
        AttachmentType::Unknown => "unknown",
    };
    let source = match &a.source {
        Source::Path(p) => Value::from(p.to_string_lossy().into_owned()),
        Source::Url(u) => Value::from(u.clone()),
        Source::ProviderFile(f) => Value::from(f.id.clone()),
        Source::Bytes(_) => Value::Null,
    };
    serde_json::json!({ "type": kind, "source": source })
}