newt-inference 0.6.1

Newt-Agent inference layer: backend trait + local Ollama/vLLM + provider-plugin host
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
//! Python bindings for `newt-inference`.
//!
//! Compiled only when the `pyo3` cargo feature is on. Exposes:
//! - `Message`, `ChatRequest`, `ChatReply` — data types.
//! - `ModelInfo` — `list_models()` row for vLLM.
//! - `LocalOllamaBackend` — async `complete` + `discover`.
//! - `LocalVllmBackend` — async `complete` + `list_models`.
//! - `BackendRegistry` — sync registry of backends.
//!
//! Async methods return Python awaitables via
//! `pyo3_async_runtimes::tokio::future_into_py`. Driving them from
//! CPython requires an asyncio event loop — `asyncio.run(...)` or
//! `pytest-asyncio` are the normal entry points.

use std::sync::Arc;
use std::time::Duration;

use crate::backend::{ChatReply, ChatRequest, InferenceBackend, Message};
use crate::local::{LocalOllamaBackend, LocalVllmBackend, ModelInfo};
use crate::registry::BackendRegistry;
use newt_core::pyo3_module::{PyNewtError, PyTier};
use newt_core::router::Tier;
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3::types::{PyModule, PyType};
use pyo3_async_runtimes::tokio::future_into_py;
use tokio::sync::Mutex;

// ---- Message ----

/// One chat message (role + content).
#[pyclass(
    name = "Message",
    module = "newt_agent._newt_agent.inference",
    frozen,
    from_py_object
)]
#[derive(Clone)]
pub struct PyMessage {
    pub inner: Message,
}

#[pymethods]
impl PyMessage {
    #[new]
    fn new(role: String, content: String) -> Self {
        Self {
            inner: Message { role, content },
        }
    }

    #[classmethod]
    fn system(_cls: &Bound<'_, PyType>, content: String) -> Self {
        Self {
            inner: Message::system(content),
        }
    }

    #[classmethod]
    fn user(_cls: &Bound<'_, PyType>, content: String) -> Self {
        Self {
            inner: Message::user(content),
        }
    }

    #[classmethod]
    fn assistant(_cls: &Bound<'_, PyType>, content: String) -> Self {
        Self {
            inner: Message::assistant(content),
        }
    }

    #[getter]
    fn role(&self) -> &str {
        &self.inner.role
    }

    #[getter]
    fn content(&self) -> &str {
        &self.inner.content
    }

    fn __repr__(&self) -> String {
        format!(
            "Message(role='{}', content='{}')",
            self.inner.role,
            self.inner.content.escape_default(),
        )
    }
}

// ---- ChatRequest ----

/// A chat completion request: messages + optional `max_tokens`.
#[pyclass(name = "ChatRequest", module = "newt_agent._newt_agent.inference")]
pub struct PyChatRequest {
    pub inner: ChatRequest,
}

#[pymethods]
impl PyChatRequest {
    #[new]
    fn new() -> Self {
        Self {
            inner: ChatRequest::new(),
        }
    }

    /// Append a system message and return `self` for chaining.
    fn system(mut slf: PyRefMut<'_, Self>, content: String) -> PyRefMut<'_, Self> {
        slf.inner.messages.push(Message::system(content));
        slf
    }

    /// Append a user message and return `self` for chaining.
    fn user(mut slf: PyRefMut<'_, Self>, content: String) -> PyRefMut<'_, Self> {
        slf.inner.messages.push(Message::user(content));
        slf
    }

    /// Append an assistant message and return `self` for chaining.
    fn assistant(mut slf: PyRefMut<'_, Self>, content: String) -> PyRefMut<'_, Self> {
        slf.inner.messages.push(Message::assistant(content));
        slf
    }

    /// Set `max_tokens` and return `self` for chaining.
    fn with_max_tokens(mut slf: PyRefMut<'_, Self>, n: u32) -> PyRefMut<'_, Self> {
        slf.inner.max_tokens = Some(n);
        slf
    }

    #[getter]
    fn messages(&self) -> Vec<PyMessage> {
        self.inner
            .messages
            .iter()
            .cloned()
            .map(|inner| PyMessage { inner })
            .collect()
    }

    #[getter]
    fn max_tokens(&self) -> Option<u32> {
        self.inner.max_tokens
    }
}

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

// ---- ChatReply ----

/// A chat completion reply (content + model id).
#[pyclass(
    name = "ChatReply",
    module = "newt_agent._newt_agent.inference",
    frozen,
    skip_from_py_object
)]
#[derive(Clone)]
pub struct PyChatReply {
    pub inner: ChatReply,
}

#[pymethods]
impl PyChatReply {
    #[new]
    fn new(content: String, model_id: String) -> Self {
        Self {
            inner: ChatReply { content, model_id },
        }
    }

    #[getter]
    fn content(&self) -> &str {
        &self.inner.content
    }

    #[getter]
    fn model_id(&self) -> &str {
        &self.inner.model_id
    }

    /// "backend=<name> model_id=<id>" — audit-trail line.
    fn audit_string(&self, backend_name: &str) -> String {
        self.inner.audit_string(backend_name)
    }

    fn __repr__(&self) -> String {
        format!(
            "ChatReply(model_id='{}', content='{}')",
            self.inner.model_id,
            self.inner.content.escape_default(),
        )
    }
}

// ---- ModelInfo ----

/// One row from `LocalVllmBackend.list_models`.
#[pyclass(
    name = "ModelInfo",
    module = "newt_agent._newt_agent.inference",
    frozen,
    skip_from_py_object
)]
#[derive(Clone)]
pub struct PyModelInfo {
    pub inner: ModelInfo,
}

#[pymethods]
impl PyModelInfo {
    #[getter]
    fn id(&self) -> &str {
        &self.inner.id
    }

    fn __repr__(&self) -> String {
        format!("ModelInfo(id='{}')", self.inner.id)
    }
}

// ---- LocalOllamaBackend ----

/// Ollama-compatible HTTP backend.
#[pyclass(
    name = "LocalOllamaBackend",
    module = "newt_agent._newt_agent.inference"
)]
pub struct PyLocalOllamaBackend {
    pub inner: Arc<LocalOllamaBackend>,
}

#[pymethods]
impl PyLocalOllamaBackend {
    #[new]
    fn new(endpoint: String, model: String) -> Self {
        Self {
            inner: Arc::new(LocalOllamaBackend::new(endpoint, model)),
        }
    }

    /// Endpoint URL the backend is bound to.
    fn endpoint(&self) -> &str {
        self.inner.endpoint()
    }

    /// Built-in fallback endpoint list (in-cluster proxy + home.lab
    /// names + localhost). Use this as the candidate list for
    /// `discover_with_candidates`.
    #[classmethod]
    fn default_endpoints(_cls: &Bound<'_, PyType>) -> Vec<String> {
        LocalOllamaBackend::default_endpoints()
    }

    /// Probe endpoints (env first, then defaults) and return a
    /// backend bound to the first reachable one. Awaitable.
    #[classmethod]
    fn discover<'py>(
        _cls: &Bound<'py, PyType>,
        py: Python<'py>,
        model: String,
    ) -> PyResult<Bound<'py, PyAny>> {
        future_into_py(py, async move {
            let backend = LocalOllamaBackend::discover(&model)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("discover: {e}")))?;
            Ok(Self {
                inner: Arc::new(backend),
            })
        })
    }

    /// Strict probe: every candidate (including any env override)
    /// must respond to `/api/tags` for selection. Awaitable.
    #[classmethod]
    fn discover_strict<'py>(
        _cls: &Bound<'py, PyType>,
        py: Python<'py>,
        model: String,
    ) -> PyResult<Bound<'py, PyAny>> {
        future_into_py(py, async move {
            let backend = LocalOllamaBackend::discover_strict(&model)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("discover_strict: {e}")))?;
            Ok(Self {
                inner: Arc::new(backend),
            })
        })
    }

    /// Issue one chat completion. Returns an awaitable yielding a
    /// `ChatReply`. Retries 5xx/connection errors transparently.
    fn complete<'py>(
        &self,
        py: Python<'py>,
        request: PyRef<'_, PyChatRequest>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let backend = self.inner.clone();
        let req = request.inner.clone();
        future_into_py(py, async move {
            let reply = backend
                .complete(req)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("complete: {e}")))?;
            Ok(PyChatReply { inner: reply })
        })
    }

    fn supports_tier(&self, tier: PyTier) -> bool {
        let t: Tier = py_tier_to_inner(tier);
        self.inner.supports_tier(t)
    }

    fn name(&self) -> &str {
        self.inner.name()
    }

    fn model_id(&self) -> &str {
        self.inner.model_id()
    }
}

// ---- LocalVllmBackend ----

/// vLLM (OpenAI-compatible) HTTP backend.
#[pyclass(name = "LocalVllmBackend", module = "newt_agent._newt_agent.inference")]
pub struct PyLocalVllmBackend {
    pub inner: Arc<LocalVllmBackend>,
}

#[pymethods]
impl PyLocalVllmBackend {
    #[new]
    fn new(endpoint: String, model: String) -> Self {
        Self {
            inner: Arc::new(LocalVllmBackend::new(endpoint, model)),
        }
    }

    fn endpoint(&self) -> &str {
        self.inner.endpoint()
    }

    fn complete<'py>(
        &self,
        py: Python<'py>,
        request: PyRef<'_, PyChatRequest>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let backend = self.inner.clone();
        let req = request.inner.clone();
        future_into_py(py, async move {
            let reply = backend
                .complete(req)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("complete: {e}")))?;
            Ok(PyChatReply { inner: reply })
        })
    }

    /// `GET /v1/models`. Returns an awaitable yielding `list[ModelInfo]`.
    fn list_models<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let backend = self.inner.clone();
        future_into_py(py, async move {
            let models = backend
                .list_models()
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("list_models: {e}")))?;
            Ok(models
                .into_iter()
                .map(|inner| PyModelInfo { inner })
                .collect::<Vec<_>>())
        })
    }

    fn supports_tier(&self, tier: PyTier) -> bool {
        let t: Tier = py_tier_to_inner(tier);
        self.inner.supports_tier(t)
    }

    fn name(&self) -> &str {
        self.inner.name()
    }

    fn model_id(&self) -> &str {
        self.inner.model_id()
    }
}

// ---- BackendRegistry ----

/// Registry of inference backends; pick by tier.
#[pyclass(name = "BackendRegistry", module = "newt_agent._newt_agent.inference")]
pub struct PyBackendRegistry {
    /// Wrap in a tokio Mutex so Python can mutate (`register`) without
    /// the GIL providing the only synchronization.
    pub inner: Arc<Mutex<BackendRegistry>>,
}

#[pymethods]
impl PyBackendRegistry {
    #[new]
    fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(BackendRegistry::new())),
        }
    }

    /// Register a `LocalOllamaBackend`.
    fn register_ollama<'py>(
        &self,
        py: Python<'py>,
        backend: PyRef<'_, PyLocalOllamaBackend>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let registry = self.inner.clone();
        let backend = backend.inner.clone();
        future_into_py(py, async move {
            let mut guard = registry.lock().await;
            // Backend trait objects require static + Send + Sync; both
            // satisfied by LocalOllamaBackend.
            let dyn_backend: Arc<dyn InferenceBackend> = backend;
            guard.register(dyn_backend);
            Ok(())
        })
    }

    /// Register a `LocalVllmBackend`.
    fn register_vllm<'py>(
        &self,
        py: Python<'py>,
        backend: PyRef<'_, PyLocalVllmBackend>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let registry = self.inner.clone();
        let backend = backend.inner.clone();
        future_into_py(py, async move {
            let mut guard = registry.lock().await;
            let dyn_backend: Arc<dyn InferenceBackend> = backend;
            guard.register(dyn_backend);
            Ok(())
        })
    }

    /// Backend names in registration order. Awaitable.
    fn names<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let registry = self.inner.clone();
        future_into_py(py, async move {
            let guard = registry.lock().await;
            Ok(guard
                .names()
                .into_iter()
                .map(str::to_string)
                .collect::<Vec<_>>())
        })
    }

    /// Backend count. Awaitable.
    fn len<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let registry = self.inner.clone();
        future_into_py(py, async move {
            let guard = registry.lock().await;
            Ok(guard.len())
        })
    }
}

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

/// Convert the Python-side `Tier` enum back into the Rust enum.
fn py_tier_to_inner(t: PyTier) -> Tier {
    match t {
        PyTier::Fast => Tier::Fast,
        PyTier::Standard => Tier::Standard,
        PyTier::Complex => Tier::Complex,
        PyTier::Review => Tier::Review,
    }
}

/// `Duration` builder exported for tests that want to tweak timeouts.
#[pyfunction]
fn duration_millis(ms: u64) -> u64 {
    Duration::from_millis(ms).as_millis() as u64
}

/// Register the `inference` submodule on the parent `_newt_agent` module.
pub fn register(py: Python<'_>, parent: &Bound<'_, PyModule>) -> PyResult<()> {
    let m = PyModule::new(py, "inference")?;
    m.add_class::<PyMessage>()?;
    m.add_class::<PyChatRequest>()?;
    m.add_class::<PyChatReply>()?;
    m.add_class::<PyModelInfo>()?;
    m.add_class::<PyLocalOllamaBackend>()?;
    m.add_class::<PyLocalVllmBackend>()?;
    m.add_class::<PyBackendRegistry>()?;
    m.add_function(wrap_pyfunction!(duration_millis, &m)?)?;
    // Re-export the core NewtError so callers don't have to import
    // from two submodules to catch backend errors.
    m.add("NewtError", py.get_type::<PyNewtError>())?;
    parent.add_submodule(&m)?;
    Ok(())
}