providers-kit 0.0.2

Portable enum-dispatch Kit over multiple model provider APIs.
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
use providers_kit::error::{ErrorKind, ErrorPhase, Operation};
use std::collections::VecDeque;
use std::convert::Infallible;
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;

use futures_util::{Stream, StreamExt};
use providers_kit::batch::{
    BatchInput, BatchJob, BatchListRequest, BatchPage, BatchResult, BatchStatus, BatchSubmitRequest,
};
use providers_kit::embedding::{EmbedRequest, EmbedResponse};
use providers_kit::files::{FileListRequest, FileObject, FilePage, FileState, FileUploadRequest};
use providers_kit::generation::{
    ContentPart, FinishReason, FunctionCall, FunctionResult, GenerateEvent, GenerateEventStream,
    GenerateRequest, GenerateResponse, Message, Role, Usage,
};
use providers_kit::models::{ModelBackend, ModelId, ModelListRequest, ModelPage, ModelSummary};
use providers_kit::runtime::HealthStatus;
use providers_kit::session::{SessionBackend, SessionConfig, SessionEvent, SessionInput};
use providers_kit::{KitError, ProviderBackend};

struct CustomProvider;

struct CustomModel {
    id: ModelId,
    continuation: CustomContinuation,
    stream_probe: Arc<StreamProbe>,
}

// The public contract requires Clone, not Debug, equality or serde. Identity
// here detects replacement of the exact returned continuation during replay.
#[derive(Clone)]
struct CustomContinuation(Arc<()>);

#[derive(Default)]
struct StreamProbe {
    polls: AtomicUsize,
    drops: AtomicUsize,
}

struct CustomStream {
    events: VecDeque<Result<GenerateEvent<CustomContinuation>, KitError>>,
    probe: Arc<StreamProbe>,
}

impl Stream for CustomStream {
    type Item = Result<GenerateEvent<CustomContinuation>, KitError>;

    fn poll_next(self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let stream = self.get_mut();
        stream.probe.polls.fetch_add(1, Ordering::SeqCst);
        Poll::Ready(stream.events.pop_front())
    }
}

impl Drop for CustomStream {
    fn drop(&mut self) {
        self.probe.drops.fetch_add(1, Ordering::SeqCst);
    }
}

struct CustomSession {
    id: String,
    model_id: ModelId,
    events: VecDeque<SessionEvent>,
}

impl CustomModel {
    fn response(
        &self,
        text: impl Into<String>,
    ) -> Result<GenerateResponse<CustomContinuation>, KitError> {
        Ok(GenerateResponse {
            model: self.id.clone(),
            message: Message::assistant_text(text)?.with_continuation(self.continuation.clone())?,
            finish_reason: Some(FinishReason::Stop),
            citations: Vec::new(),
            artifacts: Vec::new(),
            hosted_tool_outputs: Vec::new(),
            usage: Usage::default(),
        })
    }

    fn function_response(&self) -> Result<GenerateResponse<CustomContinuation>, KitError> {
        let message = Message::assistant(
            vec![
                ContentPart::Thinking {
                    text: Some("retained thinking".to_owned()),
                },
                ContentPart::Text {
                    text: "authoritative function request".to_owned(),
                },
            ],
            vec![FunctionCall::new(
                Some("caller-call".to_owned()),
                "resolve",
                serde_json::json!({"key": "answer"}),
            )?],
        )?
        .with_continuation(self.continuation.clone())?;
        Ok(GenerateResponse {
            model: self.id.clone(),
            message,
            finish_reason: Some(FinishReason::ToolCall),
            citations: Vec::new(),
            artifacts: Vec::new(),
            hosted_tool_outputs: Vec::new(),
            usage: Usage {
                input_tokens: Some(7),
                output_tokens: Some(3),
                total_tokens: Some(10),
                ..Usage::default()
            },
        })
    }

    fn assert_replay(&self, request: &GenerateRequest<CustomContinuation>) {
        let messages = request.messages();
        assert_eq!(messages.len(), 3);
        assert_eq!(messages[0].role(), Role::User);
        let assistant = &messages[1];
        let expected = self
            .function_response()
            .expect("expected response is valid");
        assert_eq!(assistant.role(), Role::Assistant);
        assert_eq!(assistant.content(), expected.message.content());
        assert_eq!(
            assistant.function_calls(),
            expected.message.function_calls()
        );
        assert!(Arc::ptr_eq(
            &assistant
                .continuation()
                .expect("exact replay continuation")
                .0,
            &self.continuation.0,
        ));
        assert_eq!(messages[2].role(), Role::Tool);
        assert_eq!(messages[2].function_results().len(), 1);
        let result = &messages[2].function_results()[0];
        assert_eq!(result.call_id(), Some("caller-call"));
        assert_eq!(result.name(), "resolve");
        assert_eq!(
            result.content(),
            [ContentPart::Json {
                value: serde_json::json!({"answer": 42}),
            }]
        );
        assert!(!result.is_error());
    }
}

impl ProviderBackend for CustomProvider {
    type Model = CustomModel;

    fn model(&self, id: ModelId) -> Result<Self::Model, KitError> {
        Ok(CustomModel {
            id,
            continuation: CustomContinuation(Arc::new(())),
            stream_probe: Arc::new(StreamProbe::default()),
        })
    }

    async fn list_models(&self, request: ModelListRequest) -> Result<ModelPage, KitError> {
        assert!(request.cursor().is_none());
        Ok(ModelPage {
            models: vec![ModelSummary {
                id: ModelId::new("custom-model")?,
                display_name: Some("Custom model".to_string()),
                description: None,
                context_window_tokens: Some(4_096),
            }],
            next_cursor: None,
        })
    }

    async fn model_info(&self, id: ModelId) -> Result<ModelSummary, KitError> {
        Ok(ModelSummary {
            id,
            display_name: Some("Custom model".to_string()),
            description: None,
            context_window_tokens: Some(4_096),
        })
    }

    async fn upload_file(&self, request: FileUploadRequest) -> Result<FileObject, KitError> {
        Ok(FileObject {
            id: "file-1".to_string(),
            file_name: Some(request.file_name().to_string()),
            size_bytes: Some(request.data().len() as u64),
            media_type: Some(request.media_type().to_string()),
            created_at: None,
            state: Some(FileState::Active),
            input_reference: None,
        })
    }

    async fn list_files(&self, _request: FileListRequest) -> Result<FilePage, KitError> {
        Ok(FilePage {
            files: Vec::new(),
            next_cursor: None,
        })
    }

    async fn file_info(&self, id: String) -> Result<FileObject, KitError> {
        Ok(FileObject {
            id,
            file_name: None,
            size_bytes: None,
            media_type: None,
            created_at: None,
            state: Some(FileState::Active),
            input_reference: None,
        })
    }

    async fn delete_file(&self, id: String) -> Result<(), KitError> {
        assert_eq!(id, "file-1");
        Ok(())
    }

    async fn download_file(
        &self,
        id: String,
        max_bytes: NonZeroUsize,
    ) -> Result<Vec<u8>, KitError> {
        assert_eq!(id, "file-1");
        assert!(max_bytes.get() >= 3);
        Ok(b"abc".to_vec())
    }

    async fn batch_status(&self, id: String) -> Result<BatchJob, KitError> {
        Ok(batch_job(id, BatchStatus::Running))
    }

    async fn cancel_batch(&self, id: String) -> Result<BatchJob, KitError> {
        Ok(batch_job(id, BatchStatus::Cancelled))
    }

    async fn batch_results(
        &self,
        id: String,
        _max_bytes: NonZeroUsize,
    ) -> Result<Vec<BatchResult<CustomContinuation>>, KitError> {
        assert_eq!(id, "batch-1");
        Ok(vec![BatchResult::Cancelled {
            custom_id: "row-1".to_string(),
        }])
    }

    async fn list_batches(&self, _request: BatchListRequest) -> Result<BatchPage, KitError> {
        Ok(BatchPage {
            jobs: vec![batch_job("batch-1".to_string(), BatchStatus::Running)],
            next_cursor: None,
        })
    }

    async fn health(&self) -> Result<HealthStatus, KitError> {
        Ok(HealthStatus {
            latency: Duration::ZERO,
        })
    }

    async fn shutdown(&self) -> Result<(), KitError> {
        Ok(())
    }
}

impl ModelBackend for CustomModel {
    type Continuation = CustomContinuation;
    type Session = CustomSession;

    fn model_id(&self) -> &ModelId {
        &self.id
    }

    async fn generate(
        &self,
        request: &GenerateRequest<CustomContinuation>,
    ) -> Result<GenerateResponse<CustomContinuation>, KitError> {
        if request.messages().last().map(Message::role) == Some(Role::Tool) {
            self.assert_replay(request);
        }
        self.response(format!(
            "response to {} message(s)",
            request.messages().len()
        ))
    }

    async fn generate_stream(
        &self,
        request: &GenerateRequest<CustomContinuation>,
    ) -> Result<GenerateEventStream<CustomContinuation>, KitError> {
        assert_eq!(request.messages().len(), 1);
        Ok(GenerateEventStream::new(CustomStream {
            events: VecDeque::from([
                Ok(GenerateEvent::Started {
                    model: self.id.clone(),
                }),
                Ok(GenerateEvent::ContentDelta {
                    delta: "first partial".to_owned(),
                }),
                Ok(GenerateEvent::ContentDelta {
                    delta: "second partial".to_owned(),
                }),
                Ok(GenerateEvent::Completed(Box::new(
                    self.function_response()?,
                ))),
            ]),
            probe: Arc::clone(&self.stream_probe),
        }))
    }

    async fn embed(&self, request: &EmbedRequest) -> Result<EmbedResponse, KitError> {
        Ok(EmbedResponse {
            vectors: request
                .inputs()
                .iter()
                .enumerate()
                .map(|(index, _)| vec![index as f32])
                .collect(),
            usage: Usage::default(),
        })
    }

    async fn submit_batch(
        &self,
        _request: &BatchSubmitRequest<CustomContinuation>,
    ) -> Result<BatchJob, KitError> {
        Ok(batch_job("batch-1".to_string(), BatchStatus::Queued))
    }

    async fn open_session(&self, _config: SessionConfig) -> Result<Self::Session, KitError> {
        Ok(CustomSession {
            id: "session-1".to_string(),
            model_id: self.id.clone(),
            events: VecDeque::new(),
        })
    }
}

impl SessionBackend for CustomSession {
    fn id(&self) -> &str {
        &self.id
    }

    fn model_id(&self) -> &ModelId {
        &self.model_id
    }

    async fn send(&mut self, input: SessionInput) -> Result<(), KitError> {
        match input {
            SessionInput::Text { text } => {
                self.events
                    .push_back(SessionEvent::TextDelta { delta: text });
                self.events.push_back(SessionEvent::Completed);
                Ok(())
            }
            _ => Err(KitError::new(
                ErrorKind::Unsupported,
                Operation::SessionSend,
                ErrorPhase::InputValidation,
            )),
        }
    }

    async fn recv(&mut self) -> Result<SessionEvent, KitError> {
        self.events.pop_front().ok_or_else(|| {
            KitError::new(
                ErrorKind::InvalidState,
                Operation::SessionReceive,
                ErrorPhase::Lifecycle,
            )
        })
    }

    async fn close(self) -> Result<(), KitError> {
        Ok(())
    }
}

fn batch_job(id: String, status: BatchStatus) -> BatchJob {
    BatchJob {
        id,
        status,
        created_at: None,
        completed_at: None,
        usage: None,
    }
}

fn assert_hierarchy<P>()
where
    P: ProviderBackend<Model = CustomModel>,
    CustomModel: ModelBackend<Continuation = CustomContinuation, Session = CustomSession>,
    CustomSession: SessionBackend,
{
}

#[tokio::test]
async fn caller_hierarchy_is_used_directly_without_sdk_normalization() {
    assert_hierarchy::<CustomProvider>();
    let provider = CustomProvider;
    let models = provider
        .list_models(ModelListRequest::default())
        .await
        .expect("direct provider should list models");
    assert_eq!(models.models.len(), 1);
    let summary = provider
        .model_info(ModelId::new("custom-model").expect("model id should validate"))
        .await
        .expect("direct provider should fetch model metadata");
    assert_eq!(summary.id.as_str(), "custom-model");

    let uploaded = provider
        .upload_file(
            FileUploadRequest::new("data.txt", "text/plain", b"abc".to_vec())
                .expect("upload should validate"),
        )
        .await
        .expect("direct provider should upload");
    assert_eq!(uploaded.id, "file-1");
    assert!(
        provider
            .list_files(FileListRequest::default())
            .await
            .expect("file list should run")
            .files
            .is_empty()
    );
    assert_eq!(
        provider
            .file_info("file-1".to_string())
            .await
            .expect("file metadata should run")
            .id,
        "file-1"
    );
    assert_eq!(
        provider
            .download_file(
                "file-1".to_string(),
                NonZeroUsize::new(8).expect("nonzero limit")
            )
            .await
            .expect("file download should run"),
        b"abc"
    );
    provider
        .delete_file("file-1".to_string())
        .await
        .expect("file delete should run");

    assert!(matches!(
        provider
            .batch_status("batch-1".to_string())
            .await
            .expect("batch status should run")
            .status,
        BatchStatus::Running
    ));
    assert!(matches!(
        provider
            .cancel_batch("batch-1".to_string())
            .await
            .expect("batch cancel should run")
            .status,
        BatchStatus::Cancelled
    ));
    let results = provider
        .batch_results(
            "batch-1".to_string(),
            NonZeroUsize::new(64).expect("nonzero limit"),
        )
        .await
        .expect("batch results should run");
    assert!(matches!(
        &results[0],
        BatchResult::Cancelled { custom_id } if custom_id == "row-1"
    ));
    assert_eq!(
        provider
            .list_batches(BatchListRequest::default())
            .await
            .expect("batch list should run")
            .jobs
            .len(),
        1
    );
    assert_eq!(
        provider.health().await.expect("health should run").latency,
        Duration::ZERO
    );

    let model = provider
        .model(ModelId::new("custom-model").expect("model id should validate"))
        .expect("provider should return its exact model");
    let request = GenerateRequest::new(vec![
        Message::<CustomContinuation>::user_text("hello").expect("message should validate"),
    ])
    .expect("request should validate");
    let response = model
        .generate(&request)
        .await
        .expect("generation should run");
    assert_eq!(response.model, *model.model_id());
    assert!(Arc::ptr_eq(
        &response.message.continuation().expect("continuation").0,
        &model.continuation.0,
    ));
    let embedded = model
        .embed(&EmbedRequest::new(vec!["hello".to_string()]).expect("embed should validate"))
        .await
        .expect("embedding should run");
    assert_eq!(embedded.vectors, vec![vec![0.0]]);
    let submitted = model
        .submit_batch(&BatchSubmitRequest::Inline {
            rows: vec![BatchInput::new("row-1", request).expect("batch row should validate")],
        })
        .await
        .expect("batch submission should run");
    assert_eq!(submitted.id, "batch-1");

    let mut session = model
        .open_session(SessionConfig::default())
        .await
        .expect("model should return its exact session");
    assert_eq!(session.id(), "session-1");
    assert_eq!(session.model_id(), model.model_id());
    session
        .send(SessionInput::Text {
            text: "echo".to_string(),
        })
        .await
        .expect("session input should send");
    assert_eq!(
        session.recv().await.expect("text event should exist"),
        SessionEvent::TextDelta {
            delta: "echo".to_string()
        }
    );
    assert_eq!(
        session.recv().await.expect("completion should exist"),
        SessionEvent::Completed
    );
    session.close().await.expect("consuming close should run");
    provider
        .shutdown()
        .await
        .expect("direct provider shutdown should run");
}

#[tokio::test]
async fn caller_stream_preserves_exact_continuation_and_normalized_function_replay() {
    let provider = CustomProvider;
    let model = provider
        .model(ModelId::new("custom-model").expect("model id should validate"))
        .expect("caller model should construct");
    let request = GenerateRequest::new(vec![
        Message::user_text("begin").expect("user message should validate"),
    ])
    .expect("request should validate");
    let mut stream = model
        .generate_stream(&request)
        .await
        .expect("caller should construct a public stream");
    assert_eq!(model.stream_probe.polls.load(Ordering::SeqCst), 0);
    assert!(matches!(
        stream.next().await,
        Some(Ok(GenerateEvent::Started { model: id })) if id == *model.model_id()
    ));
    assert_eq!(model.stream_probe.polls.load(Ordering::SeqCst), 1);
    for (index, expected) in ["first partial", "second partial"].into_iter().enumerate() {
        assert!(matches!(
            stream.next().await,
            Some(Ok(GenerateEvent::ContentDelta { delta })) if delta == expected
        ));
        assert_eq!(model.stream_probe.polls.load(Ordering::SeqCst), index + 2);
    }
    let response = match stream.next().await {
        Some(Ok(GenerateEvent::Completed(response))) => response,
        _ => panic!("the exact completed response must follow both partial deltas"),
    };
    assert_eq!(model.stream_probe.polls.load(Ordering::SeqCst), 4);
    assert_eq!(response.model, *model.model_id());
    assert_eq!(response.finish_reason, Some(FinishReason::ToolCall));
    assert_eq!(response.usage.input_tokens, Some(7));
    assert_eq!(response.usage.output_tokens, Some(3));
    assert_eq!(response.usage.total_tokens, Some(10));
    assert_eq!(
        response.message.content(),
        model
            .function_response()
            .expect("authoritative response should validate")
            .message
            .content()
    );
    assert!(Arc::ptr_eq(
        &response.message.continuation().expect("continuation").0,
        &model.continuation.0,
    ));
    assert!(serde_json::to_value(&response.message).is_err());
    assert!(stream.next().await.is_none());
    assert!(stream.next().await.is_none());
    drop(stream);
    assert_eq!(model.stream_probe.drops.load(Ordering::SeqCst), 1);

    let mut messages = request.messages().to_vec();
    messages.push(response.message);
    messages.push(
        Message::tool(vec![
            FunctionResult::new(
                Some("caller-call".to_owned()),
                "resolve",
                vec![ContentPart::Json {
                    value: serde_json::json!({"answer": 42}),
                }],
                false,
            )
            .expect("function result should validate"),
        ])
        .expect("tool message should validate"),
    );
    let continued = GenerateRequest::new(messages).expect("continued request should validate");
    let response = model
        .generate(&continued)
        .await
        .expect("caller Model should receive exact assistant replay and correlated result");
    assert_eq!(
        response.message.content(),
        [ContentPart::Text {
            text: "response to 3 message(s)".to_owned(),
        }]
    );
    provider
        .shutdown()
        .await
        .expect("provider should shut down");
}

#[tokio::test]
async fn dropping_caller_stream_releases_unpolled_or_partial_source() {
    let provider = CustomProvider;
    let model = provider
        .model(ModelId::new("custom-model").expect("model id should validate"))
        .expect("caller model should construct");
    let request = GenerateRequest::new(vec![
        Message::user_text("begin").expect("user message should validate"),
    ])
    .expect("request should validate");
    let stream = model
        .generate_stream(&request)
        .await
        .expect("unpolled stream should construct");
    drop(stream);
    assert_eq!(model.stream_probe.polls.load(Ordering::SeqCst), 0);
    assert_eq!(model.stream_probe.drops.load(Ordering::SeqCst), 1);

    let mut stream = model
        .generate_stream(&request)
        .await
        .expect("partially consumed stream should construct");
    assert!(matches!(
        stream.next().await,
        Some(Ok(GenerateEvent::Started { .. }))
    ));
    assert!(matches!(
        stream.next().await,
        Some(Ok(GenerateEvent::ContentDelta { .. }))
    ));
    drop(stream);
    assert_eq!(model.stream_probe.polls.load(Ordering::SeqCst), 2);
    assert_eq!(model.stream_probe.drops.load(Ordering::SeqCst), 2);
    provider
        .shutdown()
        .await
        .expect("provider should shut down");
}

#[tokio::test]
async fn optional_operations_default_to_unsupported_and_sessionless_models_use_infallible() {
    struct MinimalProvider;
    struct MinimalModel(ModelId);

    impl ProviderBackend for MinimalProvider {
        type Model = MinimalModel;

        fn model(&self, id: ModelId) -> Result<Self::Model, KitError> {
            Ok(MinimalModel(id))
        }

        async fn shutdown(&self) -> Result<(), KitError> {
            Ok(())
        }
    }

    impl ModelBackend for MinimalModel {
        type Continuation = ();
        type Session = Infallible;

        fn model_id(&self) -> &ModelId {
            &self.0
        }

        async fn generate(
            &self,
            _request: &GenerateRequest<()>,
        ) -> Result<GenerateResponse<()>, KitError> {
            Err(KitError::new(
                ErrorKind::Unsupported,
                Operation::Generate,
                ErrorPhase::InputValidation,
            ))
        }

        async fn generate_stream(
            &self,
            _request: &GenerateRequest<()>,
        ) -> Result<GenerateEventStream<()>, KitError> {
            Err(KitError::new(
                ErrorKind::Unsupported,
                Operation::GenerateStream,
                ErrorPhase::InputValidation,
            ))
        }

        async fn open_session(&self, _config: SessionConfig) -> Result<Infallible, KitError> {
            Err(KitError::new(
                ErrorKind::Unsupported,
                Operation::OpenSession,
                ErrorPhase::InputValidation,
            ))
        }
    }

    let provider = MinimalProvider;
    assert!(matches!(
        provider.list_models(ModelListRequest::default()).await,
        Err(ref error) if error.kind() == ErrorKind::Unsupported
    ));
    assert!(matches!(
        provider.list_files(FileListRequest::default()).await,
        Err(ref error) if error.kind() == ErrorKind::Unsupported
    ));
    let model = provider
        .model(ModelId::new("minimal").expect("model id should validate"))
        .expect("minimal model should construct");
    assert!(matches!(
        model
            .embed(&EmbedRequest::new(vec!["input".to_string()]).expect("embed should validate"))
            .await,
        Err(ref error) if error.kind() == ErrorKind::Unsupported
    ));
}