Skip to main content

maple_sdk/
types.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3use serde_json::Value;
4use uuid::Uuid;
5
6// Attestation & Key Exchange Types
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct AttestationRequest {
9    pub nonce: String,
10}
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct AttestationResponse {
14    pub attestation_document: String,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct KeyExchangeRequest {
19    pub client_public_key: String,
20    pub nonce: String,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct KeyExchangeResponse {
25    pub encrypted_session_key: String,
26    pub session_id: String,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct EncryptedRequest {
31    pub encrypted: String, // Base64-encoded (nonce + ciphertext)
32}
33
34#[derive(Debug, Clone)]
35pub struct SessionState {
36    pub session_id: Uuid,
37    pub session_key: [u8; 32],
38}
39
40// Token Management Types
41#[derive(Debug, Clone)]
42pub struct TokenPair {
43    pub access_token: String,
44    pub refresh_token: Option<String>,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct RefreshRequest {
49    pub refresh_token: String,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct RefreshResponse {
54    pub access_token: String,
55    pub refresh_token: String,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct CredentialUpdateResponse {
60    #[serde(default)]
61    pub message: String,
62    pub access_token: Option<String>,
63    pub refresh_token: Option<String>,
64}
65
66// Auth Types
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct LoginCredentials {
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub email: Option<String>,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub id: Option<Uuid>,
73    pub password: String,
74    pub client_id: Uuid,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct RegisterCredentials {
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub email: Option<String>,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub name: Option<String>,
83    pub password: String,
84    pub client_id: Uuid,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct LoginResponse {
89    pub id: Uuid,
90    pub email: Option<String>,
91    pub access_token: String,
92    pub refresh_token: String,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
96pub struct LogoutRequest {
97    pub refresh_token: String,
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub push_device_id: Option<Uuid>,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct EncryptedResponse<T> {
104    pub encrypted: String,
105    #[serde(skip)]
106    _phantom: std::marker::PhantomData<T>,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, Default)]
110pub enum NullableField<T> {
111    #[default]
112    Missing,
113    Null,
114    Value(T),
115}
116
117impl<T> NullableField<T> {
118    pub fn is_missing(&self) -> bool {
119        matches!(self, Self::Missing)
120    }
121
122    pub fn null() -> Self {
123        Self::Null
124    }
125
126    pub fn value(value: T) -> Self {
127        Self::Value(value)
128    }
129}
130
131impl<T> Serialize for NullableField<T>
132where
133    T: Serialize,
134{
135    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
136    where
137        S: Serializer,
138    {
139        match self {
140            Self::Missing | Self::Null => serializer.serialize_none(),
141            Self::Value(value) => value.serialize(serializer),
142        }
143    }
144}
145
146impl<'de, T> Deserialize<'de> for NullableField<T>
147where
148    T: Deserialize<'de>,
149{
150    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
151    where
152        D: Deserializer<'de>,
153    {
154        Ok(match Option::<T>::deserialize(deserializer)? {
155            Some(value) => Self::Value(value),
156            None => Self::Null,
157        })
158    }
159}
160
161// OAuth Types
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct OAuthInitRequest {
164    pub client_id: Uuid,
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub invite_code: Option<String>,
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct GithubAuthResponse {
171    pub auth_url: String,
172    #[serde(alias = "csrf_token")]
173    pub state: String,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct GoogleAuthResponse {
178    pub auth_url: String,
179    #[serde(alias = "csrf_token")]
180    pub state: String,
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct AppleAuthResponse {
185    pub auth_url: String,
186    pub state: String,
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub struct OAuthCallbackRequest {
191    pub code: String,
192    pub state: String,
193    pub invite_code: String,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct AppleNativeSignInRequest {
198    pub user_identifier: String,
199    pub identity_token: String,
200    pub client_id: Uuid,
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub email: Option<String>,
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub given_name: Option<String>,
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub family_name: Option<String>,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub nonce: Option<String>,
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub invite_code: Option<String>,
211}
212
213// User Profile Types
214#[derive(Debug, Clone, Serialize, Deserialize)]
215#[serde(rename_all = "lowercase")]
216pub enum LoginMethod {
217    Email,
218    Github,
219    Google,
220    Apple,
221    Guest,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
225pub struct AppUser {
226    pub id: Uuid,
227    pub name: Option<String>,
228    pub email: Option<String>,
229    pub email_verified: bool,
230    pub login_method: LoginMethod,
231    pub created_at: DateTime<Utc>,
232    pub updated_at: DateTime<Utc>,
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct UserResponse {
237    pub user: AppUser,
238}
239
240// Push Notification Types
241#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
242#[serde(rename_all = "lowercase")]
243pub enum PushPlatform {
244    Ios,
245    Android,
246}
247
248impl PushPlatform {
249    pub fn provider(self) -> PushProvider {
250        match self {
251            Self::Ios => PushProvider::Apns,
252            Self::Android => PushProvider::Fcm,
253        }
254    }
255}
256
257#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
258#[serde(rename_all = "lowercase")]
259pub enum PushProvider {
260    Apns,
261    Fcm,
262}
263
264#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
265#[serde(rename_all = "lowercase")]
266pub enum PushEnvironment {
267    Dev,
268    #[default]
269    Prod,
270}
271
272#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
273#[serde(rename_all = "snake_case")]
274pub enum PushKeyAlgorithm {
275    P256EcdhV1,
276}
277
278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
279pub struct RegisterPushDeviceRequest {
280    pub installation_id: Uuid,
281    pub platform: PushPlatform,
282    pub provider: PushProvider,
283    pub environment: PushEnvironment,
284    pub app_id: String,
285    pub push_token: String,
286    pub notification_public_key: String,
287    pub key_algorithm: PushKeyAlgorithm,
288    #[serde(default)]
289    pub supports_encrypted_preview: bool,
290    #[serde(default)]
291    pub supports_background_processing: bool,
292}
293
294impl RegisterPushDeviceRequest {
295    pub fn new(
296        installation_id: Uuid,
297        platform: PushPlatform,
298        environment: PushEnvironment,
299        app_id: impl Into<String>,
300        push_token: impl Into<String>,
301        notification_public_key: impl Into<String>,
302    ) -> Self {
303        Self {
304            installation_id,
305            platform,
306            provider: platform.provider(),
307            environment,
308            app_id: app_id.into(),
309            push_token: push_token.into(),
310            notification_public_key: notification_public_key.into(),
311            key_algorithm: PushKeyAlgorithm::P256EcdhV1,
312            supports_encrypted_preview: false,
313            supports_background_processing: false,
314        }
315    }
316
317    pub fn supports_encrypted_preview(mut self, supports_encrypted_preview: bool) -> Self {
318        self.supports_encrypted_preview = supports_encrypted_preview;
319        self
320    }
321
322    pub fn supports_background_processing(mut self, supports_background_processing: bool) -> Self {
323        self.supports_background_processing = supports_background_processing;
324        self
325    }
326}
327
328#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
329pub struct PushDevice {
330    pub id: Uuid,
331    pub object: String,
332    pub installation_id: Uuid,
333    pub platform: PushPlatform,
334    pub provider: PushProvider,
335    pub environment: PushEnvironment,
336    pub app_id: String,
337    pub key_algorithm: PushKeyAlgorithm,
338    pub supports_encrypted_preview: bool,
339    pub supports_background_processing: bool,
340    pub last_seen_at: DateTime<Utc>,
341    pub created_at: DateTime<Utc>,
342    pub updated_at: DateTime<Utc>,
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
346pub struct PushDeviceListResponse {
347    pub object: String,
348    pub data: Vec<PushDevice>,
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
352pub struct DeletedPushDeviceResponse {
353    pub id: Uuid,
354    pub object: String,
355    pub deleted: bool,
356}
357
358// Private Key Types
359#[derive(Debug, Clone, Serialize, Deserialize)]
360pub struct KeyOptions {
361    #[serde(skip_serializing_if = "Option::is_none")]
362    pub private_key_derivation_path: Option<String>,
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub seed_phrase_derivation_path: Option<String>,
365}
366
367#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct PrivateKeyResponse {
369    pub mnemonic: String,
370}
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct PrivateKeyBytesResponse {
374    pub private_key: String, // Hex encoded (64 characters for 32 bytes)
375}
376
377// Message Signing Types
378#[derive(Debug, Clone, Serialize, Deserialize)]
379#[serde(rename_all = "lowercase")]
380pub enum SigningAlgorithm {
381    Schnorr,
382    Ecdsa,
383}
384
385#[derive(Debug, Clone, Serialize, Deserialize)]
386pub struct SignMessageRequest {
387    pub message_base64: String,
388    pub algorithm: SigningAlgorithm,
389    #[serde(skip_serializing_if = "Option::is_none")]
390    pub key_options: Option<SigningKeyOptions>,
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct SigningKeyOptions {
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub private_key_derivation_path: Option<String>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub seed_phrase_derivation_path: Option<String>,
399}
400
401#[derive(Debug, Clone, Serialize, Deserialize)]
402pub struct SignMessageResponse {
403    pub signature: String,    // Base64 encoded
404    pub message_hash: String, // Hex encoded
405}
406
407// Public Key Types
408#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct PublicKeyResponse {
410    pub public_key: String, // Hex encoded
411    pub algorithm: SigningAlgorithm,
412}
413
414// Third Party Token Types
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct ThirdPartyTokenRequest {
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub audience: Option<String>,
419}
420
421#[derive(Debug, Clone, Serialize, Deserialize)]
422pub struct ThirdPartyTokenResponse {
423    pub token: String,
424}
425
426// Encryption/Decryption Types
427#[derive(Debug, Clone, Serialize, Deserialize)]
428pub struct EncryptDataRequest {
429    pub data: String,
430    #[serde(skip_serializing_if = "Option::is_none")]
431    pub key_options: Option<EncryptionKeyOptions>,
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct EncryptionKeyOptions {
436    #[serde(skip_serializing_if = "Option::is_none")]
437    pub private_key_derivation_path: Option<String>,
438    #[serde(skip_serializing_if = "Option::is_none")]
439    pub seed_phrase_derivation_path: Option<String>,
440}
441
442#[derive(Debug, Clone, Serialize, Deserialize)]
443pub struct EncryptDataResponse {
444    pub encrypted_data: String,
445}
446
447#[derive(Debug, Clone, Serialize, Deserialize)]
448pub struct DecryptDataRequest {
449    pub encrypted_data: String,
450    #[serde(skip_serializing_if = "Option::is_none")]
451    pub key_options: Option<EncryptionKeyOptions>,
452}
453
454// The decrypted response is just a string, handled directly
455
456// Account Management Types
457#[derive(Debug, Clone, Serialize, Deserialize)]
458pub struct ChangePasswordRequest {
459    pub current_password: String,
460    pub new_password: String,
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize)]
464pub struct PasswordResetRequest {
465    pub email: String,
466    pub hashed_secret: String,
467    pub client_id: Uuid,
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
471pub struct PasswordResetConfirmRequest {
472    pub email: String,
473    pub alphanumeric_code: String,
474    pub plaintext_secret: String,
475    pub new_password: String,
476    pub client_id: Uuid,
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize)]
480pub struct RequestVerificationCodeRequest {}
481
482#[derive(Debug, Clone, Serialize, Deserialize)]
483pub struct InitiateAccountDeletionRequest {
484    pub hashed_secret: String,
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct ConfirmAccountDeletionRequest {
489    pub confirmation_code: String,
490    pub plaintext_secret: String,
491}
492
493// API Key Management Types
494#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct ApiKey {
496    pub name: String,
497    pub created_at: DateTime<Utc>,
498}
499
500#[derive(Debug, Clone, Serialize, Deserialize)]
501pub struct ApiKeyListResponse {
502    pub keys: Vec<ApiKey>,
503}
504
505#[derive(Debug, Clone, Serialize, Deserialize)]
506pub struct ApiKeyCreateRequest {
507    pub name: String,
508}
509
510#[derive(Debug, Clone, Serialize, Deserialize)]
511pub struct ApiKeyCreateResponse {
512    pub key: String, // UUID format with dashes, only returned on creation
513    pub name: String,
514    pub created_at: DateTime<Utc>,
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
518pub struct Conversation {
519    pub id: Uuid,
520    pub object: String,
521    #[serde(skip_serializing_if = "Option::is_none")]
522    pub metadata: Option<Value>,
523    #[serde(skip_serializing_if = "Option::is_none")]
524    pub project_id: Option<Uuid>,
525    pub pinned: bool,
526    pub created_at: i64,
527    pub last_activity_at: i64,
528}
529
530#[derive(Debug, Clone, Serialize, Deserialize, Default)]
531pub struct ConversationCreateRequest {
532    #[serde(skip_serializing_if = "Option::is_none")]
533    pub metadata: Option<Value>,
534    #[serde(skip_serializing_if = "Option::is_none")]
535    pub project_id: Option<Uuid>,
536    #[serde(skip_serializing_if = "Option::is_none")]
537    pub pinned: Option<bool>,
538}
539
540#[derive(Debug, Clone, Serialize, Deserialize, Default)]
541pub struct ConversationUpdateRequest {
542    #[serde(skip_serializing_if = "Option::is_none")]
543    pub metadata: Option<Value>,
544    #[serde(default, skip_serializing_if = "NullableField::is_missing")]
545    pub project_id: NullableField<Uuid>,
546    #[serde(skip_serializing_if = "Option::is_none")]
547    pub pinned: Option<bool>,
548}
549
550impl ConversationUpdateRequest {
551    pub fn is_empty(&self) -> bool {
552        self.metadata.is_none() && self.project_id.is_missing() && self.pinned.is_none()
553    }
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize, Default)]
557pub struct ConversationsListParams {
558    #[serde(skip_serializing_if = "Option::is_none")]
559    pub limit: Option<i64>,
560    #[serde(skip_serializing_if = "Option::is_none")]
561    pub after: Option<Uuid>,
562    #[serde(skip_serializing_if = "Option::is_none")]
563    pub order: Option<String>,
564    #[serde(skip_serializing_if = "Option::is_none")]
565    pub project_id: Option<Uuid>,
566    #[serde(skip_serializing_if = "Option::is_none")]
567    pub unassigned_project: Option<bool>,
568    #[serde(skip_serializing_if = "Option::is_none")]
569    pub pinned: Option<bool>,
570}
571
572#[derive(Debug, Clone, Serialize, Deserialize)]
573pub struct ConversationsListResponse {
574    pub object: String,
575    pub data: Vec<Conversation>,
576    pub first_id: Option<Uuid>,
577    pub last_id: Option<Uuid>,
578    pub has_more: bool,
579}
580
581#[derive(Debug, Clone, Serialize, Deserialize)]
582pub struct ConversationsDeleteResponse {
583    pub object: String,
584    pub deleted: bool,
585}
586
587#[derive(Debug, Clone, Serialize, Deserialize)]
588pub struct BatchDeleteConversationsRequest {
589    pub ids: Vec<String>,
590}
591
592#[derive(Debug, Clone, Serialize, Deserialize)]
593pub struct BatchDeleteItemResult {
594    pub id: String,
595    pub object: String,
596    pub deleted: bool,
597    #[serde(skip_serializing_if = "Option::is_none")]
598    pub error: Option<String>,
599}
600
601#[derive(Debug, Clone, Serialize, Deserialize)]
602pub struct BatchDeleteConversationsResponse {
603    pub object: String,
604    pub data: Vec<BatchDeleteItemResult>,
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize)]
608pub struct BatchUpdateConversationProjectRequest {
609    pub ids: Vec<Uuid>,
610    pub project_id: Option<Uuid>,
611}
612
613#[derive(Debug, Clone, Serialize, Deserialize)]
614pub struct BatchUpdateConversationProjectResponse {
615    pub success: bool,
616}
617
618#[derive(Debug, Clone, Serialize, Deserialize)]
619pub struct ConversationProject {
620    pub id: Uuid,
621    pub object: String,
622    pub name: String,
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub instructions: Option<String>,
625    pub created_at: i64,
626    pub updated_at: i64,
627}
628
629#[derive(Debug, Clone, Serialize, Deserialize)]
630pub struct ConversationProjectListItem {
631    pub id: Uuid,
632    pub object: String,
633    pub name: String,
634    pub created_at: i64,
635    pub updated_at: i64,
636}
637
638#[derive(Debug, Clone, Serialize, Deserialize)]
639pub struct ConversationProjectsListResponse {
640    pub object: String,
641    pub data: Vec<ConversationProjectListItem>,
642    pub first_id: Option<Uuid>,
643    pub last_id: Option<Uuid>,
644    pub has_more: bool,
645}
646
647#[derive(Debug, Clone, Serialize, Deserialize)]
648pub struct ConversationProjectCreateRequest {
649    pub name: String,
650}
651
652#[derive(Debug, Clone, Serialize, Deserialize, Default)]
653pub struct ConversationProjectUpdateRequest {
654    #[serde(skip_serializing_if = "Option::is_none")]
655    pub name: Option<String>,
656    #[serde(default, skip_serializing_if = "NullableField::is_missing")]
657    pub instructions: NullableField<String>,
658}
659
660impl ConversationProjectUpdateRequest {
661    pub fn is_empty(&self) -> bool {
662        self.name.is_none() && self.instructions.is_missing()
663    }
664}
665
666#[derive(Debug, Clone, Serialize, Deserialize, Default)]
667pub struct ConversationProjectListParams {
668    #[serde(skip_serializing_if = "Option::is_none")]
669    pub limit: Option<i64>,
670    #[serde(skip_serializing_if = "Option::is_none")]
671    pub after: Option<Uuid>,
672    #[serde(skip_serializing_if = "Option::is_none")]
673    pub order: Option<String>,
674}
675
676// AI/OpenAI API Types
677#[derive(Debug, Clone, Serialize, Deserialize)]
678pub struct Model {
679    pub id: String,
680    #[serde(default = "default_model_object")]
681    pub object: String,
682    #[serde(skip_serializing_if = "Option::is_none")]
683    pub created: Option<i64>,
684    #[serde(skip_serializing_if = "Option::is_none")]
685    pub owned_by: Option<String>,
686}
687
688/// A catalog entry: model identity plus context and capability metadata.
689#[derive(Debug, Clone, Serialize, Deserialize)]
690pub struct CatalogModel {
691    pub id: String,
692    #[serde(default = "default_model_object")]
693    pub object: String,
694    #[serde(skip_serializing_if = "Option::is_none")]
695    pub owned_by: Option<String>,
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub context_window: Option<u64>,
698    #[serde(default, skip_serializing_if = "Option::is_none")]
699    pub max_context_tokens: Option<u64>,
700    #[serde(default, skip_serializing_if = "Option::is_none")]
701    pub capabilities: Option<CatalogCapabilities>,
702}
703
704/// Capability flags a catalog entry advertises.
705///
706/// Mirrors the server and TypeScript SDK `ModelCapabilities` contract.
707#[derive(Debug, Clone, Default, Serialize, Deserialize)]
708pub struct CatalogCapabilities {
709    #[serde(default)]
710    pub chat: bool,
711    #[serde(default)]
712    pub vision: bool,
713    #[serde(default)]
714    pub reasoning: bool,
715    #[serde(default)]
716    pub tool_use: bool,
717}
718
719/// A catalog alias resolving to a concrete model id.
720#[derive(Debug, Clone, Serialize, Deserialize)]
721pub struct CatalogAlias {
722    pub id: String,
723    #[serde(default, skip_serializing_if = "Option::is_none")]
724    pub target_model: Option<String>,
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub capabilities: Option<CatalogCapabilities>,
727}
728
729/// Default alias assignments from the catalog.
730#[derive(Debug, Clone, Default, Serialize, Deserialize)]
731pub struct CatalogDefaults {
732    #[serde(default, skip_serializing_if = "Option::is_none")]
733    pub quick: Option<String>,
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub powerful: Option<String>,
736}
737
738/// The full model catalog from `/v1/models/catalog`.
739#[derive(Debug, Clone, Default, Serialize, Deserialize)]
740pub struct ModelCatalogResponse {
741    pub object: String,
742    pub data: Vec<CatalogModel>,
743    #[serde(default)]
744    pub aliases: Vec<CatalogAlias>,
745    #[serde(default)]
746    pub defaults: CatalogDefaults,
747}
748
749fn default_model_object() -> String {
750    "model".to_string()
751}
752
753#[derive(Debug, Clone, Serialize, Deserialize)]
754pub struct ModelsResponse {
755    pub object: String,
756    pub data: Vec<Model>,
757}
758
759// Tool Calling Types
760#[derive(Debug, Clone, Serialize, Deserialize)]
761pub struct Tool {
762    #[serde(rename = "type")]
763    pub tool_type: String,
764    pub function: Function,
765}
766
767#[derive(Debug, Clone, Serialize, Deserialize)]
768pub struct Function {
769    pub name: String,
770    #[serde(skip_serializing_if = "Option::is_none")]
771    pub description: Option<String>,
772    pub parameters: Value,
773}
774
775#[derive(Debug, Clone, Serialize, Deserialize)]
776pub struct ToolCall {
777    pub id: String,
778    #[serde(rename = "type")]
779    pub tool_type: String,
780    pub function: FunctionCall,
781    #[serde(skip_serializing_if = "Option::is_none")]
782    pub index: Option<i32>,
783}
784
785#[derive(Debug, Clone, Serialize, Deserialize)]
786pub struct FunctionCall {
787    pub name: String,
788    pub arguments: String,
789}
790
791#[derive(Debug, Clone, Serialize, Deserialize)]
792pub struct ChatMessage {
793    pub role: String,
794    #[serde(default)]
795    pub content: Value, // Now accepts both string and array formats
796    #[serde(skip_serializing_if = "Option::is_none")]
797    pub tool_calls: Option<Vec<ToolCall>>,
798    #[serde(skip_serializing_if = "Option::is_none")]
799    pub reasoning_content: Option<String>,
800}
801
802#[derive(Debug, Clone, Serialize, Deserialize)]
803pub struct ChatCompletionRequest {
804    pub model: String,
805    pub messages: Vec<ChatMessage>,
806    #[serde(skip_serializing_if = "Option::is_none")]
807    pub temperature: Option<f32>,
808    #[serde(skip_serializing_if = "Option::is_none")]
809    pub max_tokens: Option<i32>,
810    #[serde(skip_serializing_if = "Option::is_none")]
811    pub stream: Option<bool>,
812    #[serde(skip_serializing_if = "Option::is_none")]
813    pub stream_options: Option<StreamOptions>,
814    #[serde(skip_serializing_if = "Option::is_none")]
815    pub tools: Option<Vec<Tool>>,
816    #[serde(skip_serializing_if = "Option::is_none")]
817    pub tool_choice: Option<Value>,
818}
819
820#[derive(Debug, Clone, Serialize, Deserialize)]
821pub struct StreamOptions {
822    pub include_usage: bool,
823}
824
825#[derive(Debug, Clone, Serialize, Deserialize)]
826pub struct ChatCompletionResponse {
827    pub id: String,
828    pub object: String,
829    pub created: i64,
830    pub model: String,
831    pub choices: Vec<ChatChoice>,
832    #[serde(skip_serializing_if = "Option::is_none")]
833    pub usage: Option<Usage>,
834}
835
836#[derive(Debug, Clone, Serialize, Deserialize)]
837pub struct ChatChoice {
838    pub index: i32,
839    pub message: ChatMessage,
840    pub finish_reason: Option<String>,
841}
842
843#[derive(Debug, Clone, Serialize, Deserialize)]
844pub struct Usage {
845    pub prompt_tokens: i32,
846    pub completion_tokens: i32,
847    pub total_tokens: i32,
848}
849
850// Streaming types - transparent Value wrapper for full passthrough of any backend JSON.
851// This avoids deserialization failures when LLMs send null fields in streaming tool_call
852// deltas or introduce new fields the SDK doesn't know about yet.
853#[derive(Debug, Clone, Serialize, Deserialize)]
854#[serde(transparent)]
855pub struct ChatCompletionChunk(pub Value);
856
857// Embeddings Types
858#[derive(Debug, Clone, Serialize, Deserialize)]
859pub struct EmbeddingRequest {
860    pub input: EmbeddingInput,
861    #[serde(default = "default_embedding_model")]
862    pub model: String,
863    #[serde(skip_serializing_if = "Option::is_none")]
864    pub encoding_format: Option<String>,
865    #[serde(skip_serializing_if = "Option::is_none")]
866    pub dimensions: Option<i32>,
867    #[serde(skip_serializing_if = "Option::is_none")]
868    pub user: Option<String>,
869}
870
871fn default_embedding_model() -> String {
872    "nomic-embed-text".to_string()
873}
874
875#[derive(Debug, Clone, Serialize, Deserialize)]
876#[serde(untagged)]
877pub enum EmbeddingInput {
878    Single(String),
879    Multiple(Vec<String>),
880}
881
882impl From<String> for EmbeddingInput {
883    fn from(s: String) -> Self {
884        EmbeddingInput::Single(s)
885    }
886}
887
888impl From<&str> for EmbeddingInput {
889    fn from(s: &str) -> Self {
890        EmbeddingInput::Single(s.to_string())
891    }
892}
893
894impl From<Vec<String>> for EmbeddingInput {
895    fn from(v: Vec<String>) -> Self {
896        EmbeddingInput::Multiple(v)
897    }
898}
899
900#[derive(Debug, Clone, Serialize, Deserialize)]
901pub struct EmbeddingResponse {
902    pub object: String,
903    pub data: Vec<EmbeddingData>,
904    pub model: String,
905    pub usage: EmbeddingUsage,
906}
907
908/// An embedding vector in the representation requested by `encoding_format`.
909#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
910#[serde(untagged)]
911pub enum EmbeddingVector {
912    Float(Vec<f64>),
913    Base64(String),
914}
915
916impl EmbeddingVector {
917    pub fn as_floats(&self) -> Option<&[f64]> {
918        match self {
919            Self::Float(values) => Some(values),
920            Self::Base64(_) => None,
921        }
922    }
923
924    pub fn as_base64(&self) -> Option<&str> {
925        match self {
926            Self::Float(_) => None,
927            Self::Base64(value) => Some(value),
928        }
929    }
930}
931
932#[derive(Debug, Clone, Serialize, Deserialize)]
933pub struct EmbeddingData {
934    pub object: String,
935    pub index: i32,
936    pub embedding: EmbeddingVector,
937}
938
939#[derive(Debug, Clone, Serialize, Deserialize)]
940pub struct EmbeddingUsage {
941    pub prompt_tokens: i32,
942    pub total_tokens: i32,
943}
944
945// Web API Types
946
947#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
948#[serde(rename_all = "snake_case")]
949pub enum WebSearchWorkflow {
950    #[default]
951    Search,
952    Images,
953    Videos,
954    News,
955    Podcasts,
956}
957
958#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
959#[serde(rename_all = "snake_case")]
960pub enum WebSearchTimeRelative {
961    Day,
962    Week,
963    Month,
964}
965
966#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
967pub struct WebSearchLens {
968    #[serde(skip_serializing_if = "Option::is_none")]
969    pub sites_included: Option<Vec<String>>,
970    #[serde(skip_serializing_if = "Option::is_none")]
971    pub sites_excluded: Option<Vec<String>>,
972    #[serde(skip_serializing_if = "Option::is_none")]
973    pub keywords_included: Option<Vec<String>>,
974    #[serde(skip_serializing_if = "Option::is_none")]
975    pub keywords_excluded: Option<Vec<String>>,
976    #[serde(skip_serializing_if = "Option::is_none")]
977    pub file_type: Option<String>,
978    #[serde(skip_serializing_if = "Option::is_none")]
979    pub time_after: Option<String>,
980    #[serde(skip_serializing_if = "Option::is_none")]
981    pub time_before: Option<String>,
982    #[serde(skip_serializing_if = "Option::is_none")]
983    pub time_relative: Option<WebSearchTimeRelative>,
984    #[serde(skip_serializing_if = "Option::is_none")]
985    pub search_region: Option<String>,
986}
987
988#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
989pub struct WebSearchFilters {
990    #[serde(skip_serializing_if = "Option::is_none")]
991    pub region: Option<String>,
992    #[serde(skip_serializing_if = "Option::is_none")]
993    pub after: Option<String>,
994    #[serde(skip_serializing_if = "Option::is_none")]
995    pub before: Option<String>,
996}
997
998#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
999pub struct WebSearchRequest {
1000    pub query: String,
1001    /// Search result class. The server defaults to [`WebSearchWorkflow::Search`].
1002    #[serde(skip_serializing_if = "Option::is_none")]
1003    pub workflow: Option<WebSearchWorkflow>,
1004    /// One-based result page, from 1 through 10.
1005    #[serde(skip_serializing_if = "Option::is_none")]
1006    pub page: Option<u8>,
1007    /// Maximum results to return, from 1 through 50. The server defaults to 10.
1008    #[serde(skip_serializing_if = "Option::is_none")]
1009    pub limit: Option<u16>,
1010    /// Whether to omit potentially unsafe content. The server defaults to true.
1011    #[serde(skip_serializing_if = "Option::is_none")]
1012    pub safe_search: Option<bool>,
1013    /// Search collection timeout in seconds, from 0.5 through 4.
1014    #[serde(skip_serializing_if = "Option::is_none")]
1015    pub timeout: Option<f64>,
1016    #[serde(skip_serializing_if = "Option::is_none")]
1017    pub lens_id: Option<String>,
1018    #[serde(skip_serializing_if = "Option::is_none")]
1019    pub lens: Option<WebSearchLens>,
1020    #[serde(skip_serializing_if = "Option::is_none")]
1021    pub filters: Option<WebSearchFilters>,
1022}
1023
1024impl WebSearchRequest {
1025    pub fn new(query: impl Into<String>) -> Self {
1026        Self {
1027            query: query.into(),
1028            workflow: None,
1029            page: None,
1030            limit: None,
1031            safe_search: None,
1032            timeout: None,
1033            lens_id: None,
1034            lens: None,
1035            filters: None,
1036        }
1037    }
1038}
1039
1040#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1041pub struct WebSearchResult {
1042    pub category: String,
1043    pub url: String,
1044    pub title: String,
1045    #[serde(default, skip_serializing_if = "Option::is_none")]
1046    pub snippet: Option<String>,
1047    #[serde(default, skip_serializing_if = "Option::is_none")]
1048    pub published_at: Option<String>,
1049}
1050
1051#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1052pub struct WebSearchResponse {
1053    #[serde(default, skip_serializing_if = "Option::is_none")]
1054    pub trace_id: Option<String>,
1055    pub results: Vec<WebSearchResult>,
1056}
1057
1058#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1059pub struct WebExtractRequest {
1060    /// Public HTTPS URLs to extract, from 1 through 10 entries.
1061    pub urls: Vec<String>,
1062    /// Bulk extraction timeout in seconds, from 0.5 through 10.
1063    #[serde(skip_serializing_if = "Option::is_none")]
1064    pub timeout: Option<f64>,
1065}
1066
1067impl WebExtractRequest {
1068    pub fn new(urls: impl IntoIterator<Item = impl Into<String>>) -> Self {
1069        Self {
1070            urls: urls.into_iter().map(Into::into).collect(),
1071            timeout: None,
1072        }
1073    }
1074}
1075
1076#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1077pub struct WebExtractPageError {
1078    pub code: String,
1079    pub message: String,
1080}
1081
1082#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1083pub struct WebExtractPage {
1084    pub url: String,
1085    #[serde(default, skip_serializing_if = "Option::is_none")]
1086    pub markdown: Option<String>,
1087    #[serde(default, skip_serializing_if = "Option::is_none")]
1088    pub error: Option<WebExtractPageError>,
1089}
1090
1091#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1092pub struct WebExtractResponse {
1093    #[serde(default, skip_serializing_if = "Option::is_none")]
1094    pub trace_id: Option<String>,
1095    pub pages: Vec<WebExtractPage>,
1096}
1097
1098// Agent API Types
1099
1100#[derive(Debug, Clone, Serialize, Deserialize)]
1101pub struct AgentChatRequest {
1102    pub input: String,
1103}
1104
1105#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1106pub struct InitMainAgentRequest {
1107    #[serde(skip_serializing_if = "Option::is_none")]
1108    pub timezone: Option<String>,
1109    #[serde(skip_serializing_if = "Option::is_none")]
1110    pub locale: Option<String>,
1111}
1112
1113#[derive(Debug, Clone, Serialize, Deserialize)]
1114pub struct InitMainAgentResponse {
1115    pub id: Uuid,
1116    pub object: String,
1117    pub kind: String,
1118    pub conversation_id: Uuid,
1119    pub display_name: String,
1120    pub created_at: i64,
1121    pub updated_at: i64,
1122    pub messages: Vec<ConversationItem>,
1123}
1124
1125#[derive(Debug, Clone, Serialize, Deserialize)]
1126pub struct CreateSubagentRequest {
1127    #[serde(skip_serializing_if = "Option::is_none")]
1128    pub display_name: Option<String>,
1129    pub purpose: String,
1130}
1131
1132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1133pub struct SetMessageReactionRequest {
1134    pub emoji: String,
1135}
1136
1137#[derive(Debug, Clone, Serialize, Deserialize)]
1138pub struct MainAgentResponse {
1139    pub id: Uuid,
1140    pub object: String,
1141    pub kind: String,
1142    pub conversation_id: Uuid,
1143    pub display_name: String,
1144    pub created_at: i64,
1145    pub updated_at: i64,
1146}
1147
1148#[derive(Debug, Clone, Serialize, Deserialize)]
1149pub struct SubagentResponse {
1150    pub id: Uuid,
1151    pub object: String,
1152    pub kind: String,
1153    pub conversation_id: Uuid,
1154    pub display_name: String,
1155    pub purpose: String,
1156    pub created_by: String,
1157    pub created_at: i64,
1158    pub updated_at: i64,
1159}
1160
1161#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1162pub struct AgentItemsListParams {
1163    #[serde(skip_serializing_if = "Option::is_none")]
1164    pub limit: Option<i64>,
1165    #[serde(skip_serializing_if = "Option::is_none")]
1166    pub after: Option<Uuid>,
1167    #[serde(skip_serializing_if = "Option::is_none")]
1168    pub order: Option<String>,
1169    #[serde(skip_serializing_if = "Option::is_none")]
1170    pub include: Option<Vec<String>>,
1171}
1172
1173#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1174pub struct ListSubagentsParams {
1175    #[serde(skip_serializing_if = "Option::is_none")]
1176    pub limit: Option<i64>,
1177    #[serde(skip_serializing_if = "Option::is_none")]
1178    pub after: Option<Uuid>,
1179    #[serde(skip_serializing_if = "Option::is_none")]
1180    pub order: Option<String>,
1181    #[serde(skip_serializing_if = "Option::is_none")]
1182    pub created_by: Option<String>,
1183}
1184
1185#[derive(Debug, Clone, Serialize, Deserialize)]
1186#[serde(tag = "type")]
1187pub enum ConversationContent {
1188    #[serde(rename = "text")]
1189    Text { text: String },
1190    #[serde(rename = "input_text")]
1191    InputText { text: String },
1192    #[serde(rename = "output_text")]
1193    OutputText { text: String },
1194    #[serde(rename = "input_image")]
1195    InputImage { image_url: String },
1196    #[serde(rename = "input_file")]
1197    InputFile { filename: String },
1198}
1199
1200#[derive(Debug, Clone, Serialize, Deserialize)]
1201#[serde(tag = "type")]
1202pub enum ReasoningContentItem {
1203    #[serde(rename = "text")]
1204    Text { text: String },
1205}
1206
1207#[derive(Debug, Clone, Serialize, Deserialize)]
1208#[serde(tag = "type")]
1209pub enum ConversationItem {
1210    #[serde(rename = "message")]
1211    Message {
1212        id: Uuid,
1213        #[serde(skip_serializing_if = "Option::is_none")]
1214        status: Option<String>,
1215        role: String,
1216        content: Vec<ConversationContent>,
1217        #[serde(skip_serializing_if = "Option::is_none")]
1218        reaction: Option<String>,
1219        #[serde(skip_serializing_if = "Option::is_none")]
1220        created_at: Option<i64>,
1221    },
1222    #[serde(rename = "function_call")]
1223    FunctionToolCall {
1224        id: Uuid,
1225        call_id: Uuid,
1226        name: String,
1227        arguments: String,
1228        #[serde(skip_serializing_if = "Option::is_none")]
1229        status: Option<String>,
1230        #[serde(skip_serializing_if = "Option::is_none")]
1231        created_at: Option<i64>,
1232    },
1233    #[serde(rename = "function_call_output")]
1234    FunctionToolCallOutput {
1235        id: Uuid,
1236        call_id: Uuid,
1237        output: String,
1238        #[serde(skip_serializing_if = "Option::is_none")]
1239        status: Option<String>,
1240        #[serde(skip_serializing_if = "Option::is_none")]
1241        created_at: Option<i64>,
1242    },
1243    #[serde(rename = "reasoning")]
1244    Reasoning {
1245        id: Uuid,
1246        content: Vec<ReasoningContentItem>,
1247        #[serde(skip_serializing_if = "Option::is_none")]
1248        status: Option<String>,
1249        #[serde(skip_serializing_if = "Option::is_none")]
1250        created_at: Option<i64>,
1251    },
1252}
1253
1254#[derive(Debug, Clone, Serialize, Deserialize)]
1255pub struct AgentItemsListResponse {
1256    pub object: String,
1257    pub data: Vec<ConversationItem>,
1258    pub first_id: Option<Uuid>,
1259    pub last_id: Option<Uuid>,
1260    pub has_more: bool,
1261}
1262
1263pub type ConversationItemsResponse = AgentItemsListResponse;
1264
1265#[derive(Debug, Clone, Serialize, Deserialize)]
1266pub struct SubagentListResponse {
1267    pub object: String,
1268    pub data: Vec<SubagentResponse>,
1269    pub first_id: Option<Uuid>,
1270    pub last_id: Option<Uuid>,
1271    pub has_more: bool,
1272}
1273
1274#[derive(Debug, Clone, Serialize, Deserialize)]
1275pub struct DeletedObjectResponse {
1276    pub id: Uuid,
1277    pub object: String,
1278    pub deleted: bool,
1279}
1280
1281// Agent SSE event types
1282#[derive(Debug, Clone, Serialize, Deserialize)]
1283pub struct AgentMessageEvent {
1284    pub message_id: Uuid,
1285    pub message: String,
1286}
1287
1288#[derive(Debug, Clone, Serialize, Deserialize)]
1289pub struct AgentReactionEvent {
1290    pub item_id: Uuid,
1291    pub emoji: String,
1292}
1293
1294#[derive(Debug, Clone, Serialize, Deserialize)]
1295pub struct AgentTypingEvent {}
1296
1297#[derive(Debug, Clone, Serialize, Deserialize)]
1298pub struct AgentDoneEvent {}
1299
1300#[derive(Debug, Clone, Serialize, Deserialize)]
1301pub struct AgentErrorEvent {
1302    pub error: String,
1303}
1304
1305/// Parsed SSE event from the agent chat stream
1306#[derive(Debug, Clone)]
1307pub enum AgentSseEvent {
1308    Message(AgentMessageEvent),
1309    Reaction(AgentReactionEvent),
1310    Typing(AgentTypingEvent),
1311    Done(AgentDoneEvent),
1312    Error(AgentErrorEvent),
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318    use serde_json::json;
1319
1320    #[test]
1321    fn nullable_field_request_serialization_distinguishes_missing_and_null() {
1322        let conversation_update = ConversationUpdateRequest::default();
1323        assert!(conversation_update.is_empty());
1324        assert_eq!(
1325            serde_json::to_value(&conversation_update).unwrap(),
1326            json!({})
1327        );
1328
1329        let conversation_update = ConversationUpdateRequest {
1330            project_id: NullableField::null(),
1331            ..Default::default()
1332        };
1333        assert!(!conversation_update.is_empty());
1334        assert_eq!(
1335            serde_json::to_value(&conversation_update).unwrap(),
1336            json!({ "project_id": null })
1337        );
1338
1339        let project_update = ConversationProjectUpdateRequest {
1340            instructions: NullableField::null(),
1341            ..Default::default()
1342        };
1343        assert!(!project_update.is_empty());
1344        assert_eq!(
1345            serde_json::to_value(&project_update).unwrap(),
1346            json!({ "instructions": null })
1347        );
1348    }
1349
1350    #[test]
1351    fn batch_update_project_request_serializes_none_as_explicit_null() {
1352        let request = BatchUpdateConversationProjectRequest {
1353            ids: vec![Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap()],
1354            project_id: None,
1355        };
1356
1357        assert_eq!(
1358            serde_json::to_value(&request).unwrap(),
1359            json!({
1360                "ids": ["550e8400-e29b-41d4-a716-446655440000"],
1361                "project_id": null
1362            })
1363        );
1364    }
1365
1366    #[test]
1367    fn credential_update_response_tolerates_missing_message() {
1368        let response: CredentialUpdateResponse =
1369            serde_json::from_value(json!({ "access_token": "new-access" })).unwrap();
1370
1371        assert_eq!(response.message, "");
1372        assert_eq!(response.access_token.as_deref(), Some("new-access"));
1373        assert_eq!(response.refresh_token, None);
1374    }
1375
1376    #[test]
1377    fn web_requests_omit_unspecified_options() {
1378        let search = WebSearchRequest::new("maple privacy");
1379        assert_eq!(
1380            serde_json::to_value(search).unwrap(),
1381            json!({ "query": "maple privacy" })
1382        );
1383
1384        let extract = WebExtractRequest::new(["https://example.com/article"]);
1385        assert_eq!(
1386            serde_json::to_value(extract).unwrap(),
1387            json!({ "urls": ["https://example.com/article"] })
1388        );
1389    }
1390
1391    #[test]
1392    fn web_responses_tolerate_absent_optional_fields() {
1393        let search: WebSearchResponse = serde_json::from_value(json!({
1394            "results": [{
1395                "category": "search",
1396                "url": "https://example.com",
1397                "title": "Example"
1398            }]
1399        }))
1400        .unwrap();
1401        assert_eq!(search.trace_id, None);
1402        assert_eq!(search.results[0].snippet, None);
1403        assert_eq!(search.results[0].published_at, None);
1404
1405        let extract: WebExtractResponse = serde_json::from_value(json!({
1406            "pages": [{ "url": "https://example.com" }]
1407        }))
1408        .unwrap();
1409        assert_eq!(extract.trace_id, None);
1410        assert_eq!(extract.pages[0].markdown, None);
1411        assert_eq!(extract.pages[0].error, None);
1412    }
1413
1414    #[test]
1415    fn embedding_response_deserializes_float_vectors() {
1416        let response: EmbeddingResponse = serde_json::from_value(json!({
1417            "object": "list",
1418            "data": [{
1419                "object": "embedding",
1420                "index": 0,
1421                "embedding": [0.1, 0.2, 0.3]
1422            }],
1423            "model": "nomic-embed-text",
1424            "usage": { "prompt_tokens": 4, "total_tokens": 4 }
1425        }))
1426        .unwrap();
1427
1428        assert_eq!(
1429            response.data[0].embedding,
1430            EmbeddingVector::Float(vec![0.1, 0.2, 0.3])
1431        );
1432        assert_eq!(
1433            response.data[0].embedding.as_floats(),
1434            Some([0.1, 0.2, 0.3].as_slice())
1435        );
1436        assert_eq!(response.data[0].embedding.as_base64(), None);
1437        assert_eq!(
1438            serde_json::to_value(&response).unwrap()["data"][0]["embedding"],
1439            json!([0.1, 0.2, 0.3])
1440        );
1441    }
1442
1443    #[test]
1444    fn embedding_response_deserializes_base64_vectors() {
1445        let response: EmbeddingResponse = serde_json::from_value(json!({
1446            "object": "list",
1447            "data": [{
1448                "object": "embedding",
1449                "index": 0,
1450                "embedding": "AQIDBA=="
1451            }],
1452            "model": "nomic-embed-text",
1453            "usage": { "prompt_tokens": 4, "total_tokens": 4 }
1454        }))
1455        .unwrap();
1456
1457        assert_eq!(
1458            response.data[0].embedding,
1459            EmbeddingVector::Base64("AQIDBA==".to_string())
1460        );
1461        assert_eq!(response.data[0].embedding.as_floats(), None);
1462        assert_eq!(response.data[0].embedding.as_base64(), Some("AQIDBA=="));
1463        assert_eq!(
1464            serde_json::to_value(&response).unwrap()["data"][0]["embedding"],
1465            json!("AQIDBA==")
1466        );
1467    }
1468
1469    #[test]
1470    fn embedding_response_rejects_unknown_vector_representations() {
1471        let response = serde_json::from_value::<EmbeddingResponse>(json!({
1472            "object": "list",
1473            "data": [{
1474                "object": "embedding",
1475                "index": 0,
1476                "embedding": { "values": [0.1, 0.2, 0.3] }
1477            }],
1478            "model": "nomic-embed-text",
1479            "usage": { "prompt_tokens": 4, "total_tokens": 4 }
1480        }));
1481
1482        assert!(response.is_err());
1483    }
1484}