letta 0.1.2

A robust Rust client for the Letta REST API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Message-related types for the Letta API.

use crate::types::common::{LettaId, Timestamp};
use bon::Builder;
use serde::{Deserialize, Serialize};

/// Message role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageRole {
    /// User message.
    User,
    /// Assistant message.
    Assistant,
    /// System message.
    System,
    /// Tool call result.
    Tool,
    /// Function call result (legacy).
    Function,
}

/// Message content variant - can be string or array.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContentVariant {
    /// Simple string content.
    String(String),
    /// Structured content items.
    Items(Vec<MessageContent>),
}

/// Message content item types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MessageContentItem {
    /// Text content.
    Text {
        /// The text content.
        text: String,
    },
    /// Image content.
    Image {
        /// The source of the image.
        source: ImageContentSource,
    },
    /// Tool call content.
    ToolCall {
        /// Tool call information.
        #[serde(flatten)]
        tool_call: ToolCall,
    },
    /// Tool return content.
    ToolReturn {
        /// Tool return information.
        #[serde(flatten)]
        tool_return: ToolReturn,
    },
    /// Reasoning content.
    Reasoning {
        /// Reasoning text.
        reasoning: String,
    },
    /// Omitted reasoning content.
    OmittedReasoning {
        /// Message indicating reasoning was omitted.
        message: String,
    },
    /// Redacted reasoning content.
    RedactedReasoning {
        /// Number of characters redacted.
        redacted_chars: u32,
    },
}

/// Message content types (legacy, keeping for compatibility).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MessageContent {
    /// Text content.
    Text {
        /// The text content.
        text: String,
    },
    /// Image content.
    Image {
        /// The source of the image.
        source: ImageContentSource,
    },
    /// Tool call content.
    ToolCall {
        /// Tool call information.
        #[serde(flatten)]
        tool_call: ToolCall,
    },
    /// Tool return content.
    ToolReturn {
        /// Tool return information.
        #[serde(flatten)]
        tool_return: ToolReturn,
    },
    /// Reasoning content.
    Reasoning {
        /// Reasoning text.
        reasoning: String,
    },
    /// Omitted reasoning content.
    OmittedReasoning {
        /// Message indicating reasoning was omitted.
        message: String,
    },
    /// Redacted reasoning content.
    RedactedReasoning {
        /// Number of characters redacted.
        redacted_chars: u32,
    },
}

/// Image URL data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageUrl {
    /// URL or base64 data.
    pub url: String,
    /// Image detail level.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// Image content source variants.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ImageContentSource {
    /// Base64 encoded image.
    Base64 {
        /// The media type for the image.
        media_type: String,
        /// The base64 encoded image data.
        data: String,
        /// What level of detail to use when processing and understanding the image.
        #[serde(skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
    },
    /// Letta-hosted image (placeholder for future use).
    Letta {
        /// Image ID or reference in Letta's system.
        id: String,
    },
    /// URL-based image.
    Url {
        /// The URL of the image.
        url: String,
    },
}

/// Tool call information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// Tool/function name.
    pub name: String,
    /// Function arguments as JSON string.
    pub arguments: String,
    /// Tool call ID.
    pub tool_call_id: String,
}

/// Message tool call (OpenAI format).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageToolCall {
    /// Tool call ID.
    pub id: String,
    /// Function details.
    pub function: MessageToolCallFunction,
    /// Tool type (always "function").
    #[serde(rename = "type")]
    pub tool_type: String,
}

/// Message tool call function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageToolCallFunction {
    /// Function name.
    pub name: String,
    /// Function arguments as JSON string.
    pub arguments: String,
}

/// Message tool return.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageToolReturn {
    /// Return status.
    pub status: String,
    /// Stdout output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdout: Option<Vec<String>>,
    /// Stderr output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stderr: Option<Vec<String>>,
}

/// Tool call function (for OpenAI-style messages).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallFunction {
    /// Function name.
    pub name: String,
    /// Function arguments as JSON string.
    pub arguments: String,
}

/// Tool return information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolReturn {
    /// Return status.
    pub status: ToolReturnStatus,
    /// Captured stdout from tool invocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdout: Option<Vec<String>>,
    /// Captured stderr from tool invocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stderr: Option<Vec<String>>,
}

/// Tool return status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolReturnStatus {
    /// Tool executed successfully.
    Success,
    /// Tool execution failed.
    Error,
}

/// Reasoning message source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningMessageSource {
    /// Reasoning from a model with native reasoning capabilities.
    ReasonerModel,
    /// Reasoning derived via prompting.
    NonReasonerModel,
}

/// Hidden reasoning message state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HiddenReasoningMessageState {
    /// Content was redacted by the provider.
    Redacted,
    /// Content was omitted by the API.
    Omitted,
}

/// Full message representation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// Message ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<LettaId>,
    /// Organization ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_id: Option<LettaId>,
    /// Agent ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<LettaId>,
    /// Model used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Message role (required).
    pub role: MessageRole,
    /// Message content as array of content items.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<Vec<MessageContentItem>>,
    /// For user/assistant: participant name. For tool/function: function name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Tool calls (for assistant messages).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<MessageToolCall>>,
    /// Tool call ID (for tool messages).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Tool returns.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_returns: Option<Vec<MessageToolReturn>>,
    /// Group ID for multi-agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_id: Option<LettaId>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Batch item ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub batch_item_id: Option<LettaId>,
    /// Created by user ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by_id: Option<LettaId>,
    /// Last updated by user ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_updated_by_id: Option<LettaId>,
    /// When the message was created.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<Timestamp>,
    /// When the message was last updated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Timestamp>,
}

/// Request to create a message.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateMessageRequest {
    /// Message role.
    pub role: MessageRole,
    /// Message content.
    pub content: String,
    /// Optional name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Tool calls (for assistant role).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ToolCall>>,
    /// Tool call ID (for tool role).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
}

/// Query parameters for listing messages.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ListMessagesParams {
    /// Limit number of results.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Pagination cursor (before).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Pagination cursor (after).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Include tool calls in response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_tool_calls: Option<bool>,
}

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

    #[test]
    fn test_message_serialization() {
        let message = Message {
            id: Some(LettaId::from_str("message-550e8400-e29b-41d4-a716-446655440000").unwrap()),
            organization_id: None,
            agent_id: Some(
                LettaId::from_str("agent-550e8400-e29b-41d4-a716-446655440001").unwrap(),
            ),
            role: MessageRole::User,
            content: Some(vec![MessageContentItem::Text {
                text: "Hello, world!".to_string(),
            }]),
            name: None,
            tool_calls: None,
            tool_call_id: None,
            model: None,
            step_id: None,
            otid: None,
            tool_returns: None,
            group_id: None,
            sender_id: None,
            batch_item_id: None,
            created_by_id: None,
            last_updated_by_id: None,
            created_at: Some(chrono::Utc::now()),
            updated_at: None,
        };

        let json = serde_json::to_string(&message).unwrap();
        let deserialized: Message = serde_json::from_str(&json).unwrap();
        assert_eq!(message.role, deserialized.role);
    }

    #[test]
    fn test_message_content_variants() {
        let text_content = MessageContentItem::Text {
            text: "Hello".to_string(),
        };
        let json = serde_json::to_string(&text_content).unwrap();
        assert!(json.contains("\"type\":\"text\""));

        let tool_call = MessageContentItem::ToolCall {
            tool_call: ToolCall {
                name: "get_weather".to_string(),
                arguments: r#"{"location": "Seattle"}"#.to_string(),
                tool_call_id: "call-123".to_string(),
            },
        };
        let json = serde_json::to_string(&tool_call).unwrap();
        assert!(json.contains("\"type\":\"tool_call\""));
    }

    #[test]
    fn test_message_role_serialization() {
        assert_eq!(
            serde_json::to_string(&MessageRole::User).unwrap(),
            "\"user\""
        );
        assert_eq!(
            serde_json::to_string(&MessageRole::Assistant).unwrap(),
            "\"assistant\""
        );
        assert_eq!(
            serde_json::to_string(&MessageRole::Tool).unwrap(),
            "\"tool\""
        );
    }
}

// =============================================================================
// Letta-specific Message Types
// =============================================================================

/// Message type values used by Letta.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageType {
    /// System message.
    #[serde(rename = "system_message")]
    SystemMessage,
    /// User message.
    #[serde(rename = "user_message")]
    UserMessage,
    /// Assistant response message.
    #[serde(rename = "assistant_message")]
    AssistantMessage,
    /// Reasoning/thinking message.
    #[serde(rename = "reasoning_message")]
    ReasoningMessage,
    /// Hidden/redacted reasoning message.
    #[serde(rename = "hidden_reasoning_message")]
    HiddenReasoningMessage,
    /// Tool call invocation message.
    #[serde(rename = "tool_call_message")]
    ToolCallMessage,
    /// Tool execution result message.
    #[serde(rename = "tool_return_message")]
    ToolReturnMessage,
    /// Stop reason indicator.
    #[serde(rename = "stop_reason")]
    StopReason,
    /// Usage statistics.
    #[serde(rename = "usage_statistics")]
    UsageStatistics,
    /// Any other message type.
    #[serde(other)]
    Other,
}

/// Union type for all Letta message types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "message_type", rename_all = "snake_case")]
pub enum LettaMessageUnion {
    /// System message from Letta.
    SystemMessage(SystemMessage),
    /// User message to Letta.
    UserMessage(UserMessage),
    /// Assistant response from Letta.
    AssistantMessage(AssistantMessage),
    /// Internal reasoning/thinking message.
    ReasoningMessage(ReasoningMessage),
    /// Hidden or redacted reasoning message.
    HiddenReasoningMessage(HiddenReasoningMessage),
    /// Tool call invocation message.
    ToolCallMessage(ToolCallMessage),
    /// Tool execution result message.
    ToolReturnMessage(ToolReturnMessage),
}

/// System message from Letta.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// System message content.
    pub content: String,
}

/// User message to Letta.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// User message content.
    pub content: String,
}

/// Assistant message from Letta.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// Assistant response content.
    pub content: String,
}

/// Reasoning message (internal thoughts).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// Source of reasoning.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<ReasoningMessageSource>,
    /// Reasoning content (internal thoughts).
    pub reasoning: String,
    /// Model-generated signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

/// Hidden reasoning message (redacted thoughts).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HiddenReasoningMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// State of hidden reasoning.
    pub state: HiddenReasoningMessageState,
    /// Hidden reasoning content (redacted).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hidden_reasoning: Option<String>,
}

/// Tool call message.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// Tool call information.
    pub tool_call: ToolCall,
}

/// Tool return message.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolReturnMessage {
    /// Message ID.
    pub id: LettaId,
    /// Message timestamp.
    pub date: Timestamp,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Step ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_id: Option<LettaId>,
    /// Tool return value as string.
    pub tool_return: String,
    /// Status of the tool call.
    pub status: ToolReturnStatus,
    /// Tool call ID this is responding to.
    pub tool_call_id: String,
    /// Captured stdout from tool invocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdout: Option<Vec<String>>,
    /// Captured stderr from tool invocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stderr: Option<Vec<String>>,
}

/// Request to create a message for Letta agents.
#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
pub struct MessageCreate {
    /// Message role.
    pub role: MessageRole,
    /// Message content (can be string or complex content).
    pub content: MessageCreateContent,
    /// Optional participant name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Offline threading ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otid: Option<String>,
    /// Sender ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_id: Option<LettaId>,
    /// Batch item ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub batch_item_id: Option<LettaId>,
    /// Group ID for multi-agent conversations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_id: Option<LettaId>,
}

impl Default for MessageCreate {
    fn default() -> Self {
        Self {
            role: MessageRole::User,
            content: MessageCreateContent::String(String::new()),
            name: None,
            otid: None,
            sender_id: None,
            batch_item_id: None,
            group_id: None,
        }
    }
}

impl MessageCreate {
    /// Create a simple user message.
    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: MessageRole::User,
            content: MessageCreateContent::String(content.into()),
            ..Default::default()
        }
    }

    /// Create a simple assistant message.
    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: MessageRole::Assistant,
            content: MessageCreateContent::String(content.into()),
            name: None,
            otid: None,
            sender_id: None,
            batch_item_id: None,
            group_id: None,
        }
    }

    /// Create a simple system message.
    pub fn system(content: impl Into<String>) -> Self {
        Self {
            role: MessageRole::System,
            content: MessageCreateContent::String(content.into()),
            name: None,
            otid: None,
            sender_id: None,
            batch_item_id: None,
            group_id: None,
        }
    }
}

/// Content for message creation (can be simple string or complex types).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageCreateContent {
    /// Simple text string.
    String(String),
    /// Complex content parts for multi-modal messages.
    ContentParts(Vec<ContentPart>),
}

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

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

impl From<Vec<String>> for MessageCreateContent {
    fn from(parts: Vec<String>) -> Self {
        Self::ContentParts(
            parts
                .into_iter()
                .map(|text| ContentPart::Text(TextContent { text }))
                .collect(),
        )
    }
}

/// Individual content part for multi-modal messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    /// Text content part.
    Text(TextContent),
    /// Image content part.
    Image(ImageContent),
}

/// Text content part.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextContent {
    /// The text content.
    pub text: String,
}

/// Image content part.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageContent {
    /// Image URL information.
    pub image_url: ImageUrl,
}

/// Response from creating/sending messages to Letta.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LettaResponse {
    /// Messages in the conversation.
    pub messages: Vec<LettaMessageUnion>,
    /// Reason processing stopped.
    pub stop_reason: LettaStopReason,
    /// Token usage statistics.
    pub usage: LettaUsageStatistics,
}

/// Stop reason types supported by Letta.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReasonType {
    /// End of conversation turn.
    EndTurn,
    /// Error occurred.
    Error,
    /// Invalid tool call.
    InvalidToolCall,
    /// Maximum steps reached.
    MaxSteps,
    /// No tool call made.
    NoToolCall,
    /// Tool rule triggered.
    ToolRule,
}

/// Reason why message processing stopped.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LettaStopReason {
    /// The reason processing stopped.
    pub stop_reason: StopReasonType,
}

/// Token usage statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LettaUsageStatistics {
    /// Tokens used for completion.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completion_tokens: Option<i32>,
    /// Tokens used for prompt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_tokens: Option<i32>,
    /// Total tokens used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_tokens: Option<i32>,
    /// Step count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_count: Option<i32>,
    /// Messages generated per step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub steps_messages: Option<Vec<Vec<Message>>>,
    /// Background task run IDs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_ids: Option<Vec<LettaId>>,
}

/// Parameters for creating messages.
#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]
pub struct CreateMessagesRequest {
    /// Messages to send.
    pub messages: Vec<MessageCreate>,
    /// Maximum processing steps.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_steps: Option<i32>,
    /// Use assistant message format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_assistant_message: Option<bool>,
    /// Assistant message tool name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assistant_message_tool_name: Option<String>,
    /// Assistant message tool kwargs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assistant_message_tool_kwargs: Option<String>,
    /// Filter response message types.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_return_message_types: Option<Vec<MessageType>>,
}

/// Parameters for listing messages.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ListMessagesRequest {
    /// Pagination cursor (after).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination cursor (before).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Maximum number of messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i32>,
    /// Filter by group ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_id: Option<LettaId>,
    /// Use assistant message format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_assistant_message: Option<bool>,
    /// Assistant message tool name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assistant_message_tool_name: Option<String>,
    /// Assistant message tool kwargs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assistant_message_tool_kwargs: Option<String>,
}

// =============================================================================
// Message Update Types
// =============================================================================

/// Request to modify/update a message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "message_type", rename_all = "snake_case")]
pub enum UpdateMessageRequest {
    /// Update a system message.
    #[serde(rename = "system_message")]
    SystemMessage(UpdateSystemMessage),
    /// Update a user message.
    #[serde(rename = "user_message")]
    UserMessage(UpdateUserMessage),
    /// Update a reasoning message.
    #[serde(rename = "reasoning_message")]
    ReasoningMessage(UpdateReasoningMessage),
    /// Update an assistant message.
    #[serde(rename = "assistant_message")]
    AssistantMessage(UpdateAssistantMessage),
}

/// Update system message request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateSystemMessage {
    /// Updated message content.
    pub content: String,
}

/// Update user message request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateUserMessage {
    /// Updated message content.
    pub content: UpdateUserMessageContent,
}

/// Content for updating user messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateUserMessageContent {
    /// Simple text content.
    String(String),
    /// Complex content parts.
    ContentParts(Vec<ContentPart>),
}

/// Update reasoning message request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateReasoningMessage {
    /// Updated reasoning content.
    pub reasoning: String,
}

/// Update assistant message request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateAssistantMessage {
    /// Updated message content.
    pub content: UpdateAssistantMessageContent,
}

/// Content for updating assistant messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateAssistantMessageContent {
    /// Simple text content.
    String(String),
    /// Complex content parts.
    ContentParts(Vec<ContentPart>),
}

// Note: Async message/job types (Run, JobStatus, JobType) have been moved to types/runs.rs