ollama-client 0.1.0

Async and blocking Rust client for the Ollama 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
//! Blocking (synchronous) client and builders.

use crate::error::Result;
use crate::types::chat::{ChatResponse, ChatStreamChunk};
use crate::types::common::{Message, Options, Tool};
use crate::types::embed::{EmbedInput, EmbedResponse};
use crate::types::generate::{GenerateResponse, GenerateStreamChunk};
use crate::types::models::*;

const DEFAULT_BASE_URL: &str = "http://localhost:11434";

/// Blocking Ollama API client.
///
/// Wraps the async [`OllamaClient`](crate::OllamaClient) and runs it on an
/// internal tokio runtime.
pub struct BlockingClient {
    inner: crate::OllamaClient,
    rt: tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingClient")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

fn build_runtime() -> std::result::Result<tokio::runtime::Runtime, std::io::Error> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
}

impl BlockingClient {
    /// Creates a new blocking client connecting to `http://localhost:11434`.
    ///
    /// # Panics
    ///
    /// Panics if the runtime or HTTP client cannot be built.
    /// Use [`BlockingClient::try_new()`] for a fallible alternative.
    pub fn new() -> Self {
        Self::try_new().expect("failed to create BlockingClient")
    }

    /// Fallible constructor connecting to `http://localhost:11434`.
    pub fn try_new() -> Result<Self> {
        Self::try_with_base_url(DEFAULT_BASE_URL)
    }

    /// Creates a new blocking client with a custom base URL.
    ///
    /// # Panics
    ///
    /// Panics if `base_url` is not a valid HTTP/HTTPS URL.
    /// Use [`BlockingClient::try_with_base_url()`] for a fallible alternative.
    pub fn with_base_url(base_url: impl Into<String>) -> Self {
        Self::try_with_base_url(base_url).expect("invalid base URL")
    }

    /// Fallible constructor with a custom base URL.
    pub fn try_with_base_url(base_url: impl Into<String>) -> Result<Self> {
        let rt = build_runtime().map_err(crate::error::OllamaError::Io)?;
        let inner = crate::OllamaClient::try_with_base_url(base_url)?;
        Ok(Self { inner, rt })
    }

    /// Creates a blocking client from an existing `reqwest::Client` and base URL.
    ///
    /// # Panics
    ///
    /// Panics if `base_url` is not a valid HTTP/HTTPS URL.
    pub fn from_reqwest(client: reqwest::Client, base_url: impl Into<String>) -> Self {
        Self::try_from_reqwest(client, base_url).expect("invalid base URL")
    }

    /// Fallible constructor from an existing `reqwest::Client` and base URL.
    pub fn try_from_reqwest(client: reqwest::Client, base_url: impl Into<String>) -> Result<Self> {
        let rt = build_runtime().map_err(crate::error::OllamaError::Io)?;
        let inner = crate::OllamaClient::try_from_reqwest(client, base_url)?;
        Ok(Self { inner, rt })
    }

    /// Returns a reference to the underlying async client.
    pub fn inner(&self) -> &crate::OllamaClient {
        &self.inner
    }

    // ── Chat ──

    pub fn chat(&self) -> BlockingChatRequestBuilder<'_> {
        BlockingChatRequestBuilder {
            inner: self.inner.chat(),
            rt: &self.rt,
        }
    }

    // ── Generate ──

    pub fn generate(&self) -> BlockingGenerateRequestBuilder<'_> {
        BlockingGenerateRequestBuilder {
            inner: self.inner.generate(),
            rt: &self.rt,
        }
    }

    // ── Embed ──

    pub fn embed(&self) -> BlockingEmbedRequestBuilder<'_> {
        BlockingEmbedRequestBuilder {
            inner: self.inner.embed(),
            rt: &self.rt,
        }
    }

    // ── Model management ──

    pub fn list_models(&self) -> Result<ListModelsResponse> {
        self.rt.block_on(self.inner.list_models())
    }

    pub fn show_model(&self) -> BlockingShowModelRequestBuilder<'_> {
        BlockingShowModelRequestBuilder {
            inner: self.inner.show_model(),
            rt: &self.rt,
        }
    }

    pub fn copy_model(
        &self,
        source: impl Into<String>,
        destination: impl Into<String>,
    ) -> Result<()> {
        self.rt.block_on(self.inner.copy_model(source, destination))
    }

    pub fn delete_model(&self, model: impl Into<String>) -> Result<()> {
        self.rt.block_on(self.inner.delete_model(model))
    }

    pub fn pull_model(&self) -> BlockingPullModelRequestBuilder<'_> {
        BlockingPullModelRequestBuilder {
            inner: self.inner.pull_model(),
            rt: &self.rt,
        }
    }

    pub fn push_model(&self) -> BlockingPushModelRequestBuilder<'_> {
        BlockingPushModelRequestBuilder {
            inner: self.inner.push_model(),
            rt: &self.rt,
        }
    }

    pub fn create_model(&self) -> BlockingCreateModelRequestBuilder<'_> {
        BlockingCreateModelRequestBuilder {
            inner: self.inner.create_model(),
            rt: &self.rt,
        }
    }

    pub fn list_running(&self) -> Result<ListRunningResponse> {
        self.rt.block_on(self.inner.list_running())
    }

    // ── Blobs ──

    pub fn check_blob(&self, digest: &str) -> Result<bool> {
        self.rt.block_on(self.inner.check_blob(digest))
    }

    pub fn upload_blob(&self, digest: &str, data: Vec<u8>) -> Result<()> {
        self.rt.block_on(self.inner.upload_blob(digest, data))
    }

    // ── Version ──

    pub fn version(&self) -> Result<VersionResponse> {
        self.rt.block_on(self.inner.version())
    }
}

impl Default for BlockingClient {
    fn default() -> Self {
        Self::new()
    }
}

// ────────────────────────────────────────────────────────────────
// Blocking stream wrapper
// ────────────────────────────────────────────────────────────────

/// Blocking iterator over streaming items.
pub struct BlockingStream<'a, T> {
    inner: std::pin::Pin<Box<dyn futures_core::Stream<Item = Result<T>> + 'a>>,
    rt: &'a tokio::runtime::Runtime,
}

impl<T> std::fmt::Debug for BlockingStream<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingStream").finish_non_exhaustive()
    }
}

impl<T> Iterator for BlockingStream<'_, T> {
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        use tokio_stream::StreamExt;
        self.rt.block_on(self.inner.next())
    }
}

// ────────────────────────────────────────────────────────────────
// Blocking builders
// ────────────────────────────────────────────────────────────────

// ── Chat ──

/// Blocking builder for a chat request.
#[must_use]
pub struct BlockingChatRequestBuilder<'a> {
    inner: crate::client::ChatRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingChatRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingChatRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingChatRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    pub fn messages(mut self, messages: Vec<Message>) -> Self {
        self.inner = self.inner.messages(messages);
        self
    }

    pub fn format(mut self, format: serde_json::Value) -> Self {
        self.inner = self.inner.format(format);
        self
    }

    pub fn tools(mut self, tools: Vec<Tool>) -> Self {
        self.inner = self.inner.tools(tools);
        self
    }

    pub fn think(mut self, think: bool) -> Self {
        self.inner = self.inner.think(think);
        self
    }

    pub fn options(mut self, options: Options) -> Self {
        self.inner = self.inner.options(options);
        self
    }

    pub fn temperature(mut self, temp: f64) -> Self {
        self.inner = self.inner.temperature(temp);
        self
    }

    pub fn top_k(mut self, top_k: u32) -> Self {
        self.inner = self.inner.top_k(top_k);
        self
    }

    pub fn top_p(mut self, top_p: f64) -> Self {
        self.inner = self.inner.top_p(top_p);
        self
    }

    pub fn num_ctx(mut self, num_ctx: u32) -> Self {
        self.inner = self.inner.num_ctx(num_ctx);
        self
    }

    pub fn keep_alive(mut self, keep_alive: impl Into<String>) -> Self {
        self.inner = self.inner.keep_alive(keep_alive);
        self
    }

    pub fn send(self) -> Result<ChatResponse> {
        self.rt.block_on(self.inner.send())
    }

    pub fn send_stream(self) -> Result<BlockingStream<'a, ChatStreamChunk>> {
        let stream = self.rt.block_on(self.inner.send_stream())?;
        Ok(BlockingStream {
            inner: Box::pin(stream),
            rt: self.rt,
        })
    }
}

// ── Generate ──

/// Blocking builder for a generate request.
#[must_use]
pub struct BlockingGenerateRequestBuilder<'a> {
    inner: crate::client::GenerateRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingGenerateRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingGenerateRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingGenerateRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.inner = self.inner.prompt(prompt);
        self
    }

    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
        self.inner = self.inner.suffix(suffix);
        self
    }

    pub fn images(mut self, images: Vec<String>) -> Self {
        self.inner = self.inner.images(images);
        self
    }

    pub fn format(mut self, format: serde_json::Value) -> Self {
        self.inner = self.inner.format(format);
        self
    }

    pub fn system(mut self, system: impl Into<String>) -> Self {
        self.inner = self.inner.system(system);
        self
    }

    pub fn think(mut self, think: bool) -> Self {
        self.inner = self.inner.think(think);
        self
    }

    pub fn raw(mut self, raw: bool) -> Self {
        self.inner = self.inner.raw(raw);
        self
    }

    pub fn keep_alive(mut self, keep_alive: impl Into<String>) -> Self {
        self.inner = self.inner.keep_alive(keep_alive);
        self
    }

    pub fn options(mut self, options: Options) -> Self {
        self.inner = self.inner.options(options);
        self
    }

    pub fn temperature(mut self, temp: f64) -> Self {
        self.inner = self.inner.temperature(temp);
        self
    }

    pub fn context(mut self, context: Vec<i64>) -> Self {
        self.inner = self.inner.context(context);
        self
    }

    pub fn send(self) -> Result<GenerateResponse> {
        self.rt.block_on(self.inner.send())
    }

    pub fn send_stream(self) -> Result<BlockingStream<'a, GenerateStreamChunk>> {
        let stream = self.rt.block_on(self.inner.send_stream())?;
        Ok(BlockingStream {
            inner: Box::pin(stream),
            rt: self.rt,
        })
    }
}

// ── Embed ──

/// Blocking builder for an embed request.
#[must_use]
pub struct BlockingEmbedRequestBuilder<'a> {
    inner: crate::client::EmbedRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingEmbedRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingEmbedRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingEmbedRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    pub fn input(mut self, input: impl Into<EmbedInput>) -> Self {
        self.inner = self.inner.input(input);
        self
    }

    pub fn truncate(mut self, truncate: bool) -> Self {
        self.inner = self.inner.truncate(truncate);
        self
    }

    pub fn dimensions(mut self, dimensions: u32) -> Self {
        self.inner = self.inner.dimensions(dimensions);
        self
    }

    pub fn keep_alive(mut self, keep_alive: impl Into<String>) -> Self {
        self.inner = self.inner.keep_alive(keep_alive);
        self
    }

    pub fn options(mut self, options: Options) -> Self {
        self.inner = self.inner.options(options);
        self
    }

    pub fn send(self) -> Result<EmbedResponse> {
        self.rt.block_on(self.inner.send())
    }
}

// ── Show model ──

/// Blocking builder for a show-model request.
#[must_use]
pub struct BlockingShowModelRequestBuilder<'a> {
    inner: crate::client::ShowModelRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingShowModelRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingShowModelRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingShowModelRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    pub fn verbose(mut self, verbose: bool) -> Self {
        self.inner = self.inner.verbose(verbose);
        self
    }

    pub fn send(self) -> Result<ShowModelResponse> {
        self.rt.block_on(self.inner.send())
    }
}

// ── Pull model ──

/// Blocking builder for a pull-model request.
#[must_use]
pub struct BlockingPullModelRequestBuilder<'a> {
    inner: crate::client::PullModelRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingPullModelRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingPullModelRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingPullModelRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    /// Enable insecure mode (skip TLS certificate verification on the Ollama server side).
    ///
    /// **Warning:** This disables TLS certificate verification for registry operations.
    /// Use only in local development or testing environments, never in production.
    pub fn insecure(mut self, insecure: bool) -> Self {
        self.inner = self.inner.insecure(insecure);
        self
    }

    pub fn send(self) -> Result<PullModelStatus> {
        self.rt.block_on(self.inner.send())
    }

    pub fn send_stream(self) -> Result<BlockingStream<'a, PullModelStatus>> {
        let stream = self.rt.block_on(self.inner.send_stream())?;
        Ok(BlockingStream {
            inner: Box::pin(stream),
            rt: self.rt,
        })
    }
}

// ── Push model ──

/// Blocking builder for a push-model request.
#[must_use]
pub struct BlockingPushModelRequestBuilder<'a> {
    inner: crate::client::PushModelRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingPushModelRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingPushModelRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingPushModelRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    /// Enable insecure mode (skip TLS certificate verification on the Ollama server side).
    ///
    /// **Warning:** This disables TLS certificate verification for registry operations.
    /// Use only in local development or testing environments, never in production.
    pub fn insecure(mut self, insecure: bool) -> Self {
        self.inner = self.inner.insecure(insecure);
        self
    }

    pub fn send(self) -> Result<PushModelStatus> {
        self.rt.block_on(self.inner.send())
    }

    pub fn send_stream(self) -> Result<BlockingStream<'a, PushModelStatus>> {
        let stream = self.rt.block_on(self.inner.send_stream())?;
        Ok(BlockingStream {
            inner: Box::pin(stream),
            rt: self.rt,
        })
    }
}

// ── Create model ──

/// Blocking builder for a create-model request.
#[must_use]
pub struct BlockingCreateModelRequestBuilder<'a> {
    inner: crate::client::CreateModelRequestBuilder<'a>,
    rt: &'a tokio::runtime::Runtime,
}

impl std::fmt::Debug for BlockingCreateModelRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingCreateModelRequestBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl<'a> BlockingCreateModelRequestBuilder<'a> {
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    pub fn from_model(mut self, from: impl Into<String>) -> Self {
        self.inner = self.inner.from_model(from);
        self
    }

    pub fn system(mut self, system: impl Into<String>) -> Self {
        self.inner = self.inner.system(system);
        self
    }

    pub fn template(mut self, template: impl Into<String>) -> Self {
        self.inner = self.inner.template(template);
        self
    }

    pub fn parameters(mut self, parameters: serde_json::Value) -> Self {
        self.inner = self.inner.parameters(parameters);
        self
    }

    pub fn quantize(mut self, quantize: impl Into<String>) -> Self {
        self.inner = self.inner.quantize(quantize);
        self
    }

    pub fn license(mut self, license: serde_json::Value) -> Self {
        self.inner = self.inner.license(license);
        self
    }

    pub fn messages(mut self, messages: Vec<Message>) -> Self {
        self.inner = self.inner.messages(messages);
        self
    }

    pub fn send(self) -> Result<CreateModelStatus> {
        self.rt.block_on(self.inner.send())
    }

    pub fn send_stream(self) -> Result<BlockingStream<'a, CreateModelStatus>> {
        let stream = self.rt.block_on(self.inner.send_stream())?;
        Ok(BlockingStream {
            inner: Box::pin(stream),
            rt: self.rt,
        })
    }
}