hoosh 1.3.0

AI inference gateway — multi-provider LLM routing, local model serving, speech-to-text, and token budget management
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
//! Request/response types for the OpenAI-compatible HTTP API.

use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::server::AppState;

// ---------------------------------------------------------------------------
// Chat completions
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
pub(crate) struct ChatRequest {
    pub model: String,
    pub messages: Vec<ChatMessage>,
    #[serde(default)]
    pub max_tokens: Option<u32>,
    #[serde(default)]
    pub temperature: Option<f64>,
    #[serde(default)]
    pub top_p: Option<f64>,
    #[serde(default)]
    pub stream: bool,
    /// Tool definitions the model may call.
    #[serde(default)]
    pub tools: Vec<crate::tools::ToolDefinition>,
    /// How the model should choose tools.
    #[serde(default)]
    pub tool_choice: Option<crate::tools::ToolChoice>,
    /// Token budget pool name (defaults to "default").
    #[serde(default = "default_pool_name")]
    pub pool: String,
}

fn default_pool_name() -> String {
    "default".into()
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub(crate) struct ChatMessage {
    pub role: String,
    pub content: crate::inference::MessageContent,
    #[serde(default)]
    pub tool_call_id: Option<String>,
    #[serde(default)]
    pub tool_calls: Vec<crate::tools::ToolCall>,
}

#[derive(Serialize)]
pub(crate) struct ChatCompletionResponse {
    pub id: String,
    pub object: &'static str,
    pub created: i64,
    pub model: String,
    pub choices: Vec<ChatChoice>,
    pub usage: ChatUsage,
}

#[derive(Serialize)]
pub(crate) struct ChatChoice {
    pub index: u32,
    pub message: ChatResponseMessage,
    pub finish_reason: &'static str,
}

#[derive(Serialize)]
pub(crate) struct ChatResponseMessage {
    pub role: &'static str,
    pub content: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<crate::tools::ToolCall>,
}

#[derive(Serialize)]
pub(crate) struct ChatUsage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

// ---------------------------------------------------------------------------
// Error response
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct ErrorResponse {
    pub error: ErrorDetail,
}

#[derive(Serialize)]
pub(crate) struct ErrorDetail {
    pub message: String,
    pub r#type: &'static str,
    pub code: Option<String>,
}

pub(crate) fn error_response(
    status: axum::http::StatusCode,
    message: impl Into<String>,
) -> impl axum::response::IntoResponse {
    (
        status,
        axum::Json(ErrorResponse {
            error: ErrorDetail {
                message: message.into(),
                r#type: "error",
                code: None,
            },
        }),
    )
}

// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct ModelsResponse {
    pub object: &'static str,
    pub data: Vec<ModelObject>,
}

#[derive(Serialize)]
pub(crate) struct ModelObject {
    pub id: String,
    pub object: &'static str,
    pub owned_by: String,
}

// ---------------------------------------------------------------------------
// Health
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct HealthResponse {
    pub status: &'static str,
    pub version: &'static str,
    pub providers_configured: usize,
}

#[derive(Serialize)]
pub(crate) struct ProviderHealth {
    pub provider: String,
    pub base_url: String,
    pub enabled: bool,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub consecutive_failures: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
}

// ---------------------------------------------------------------------------
// Token budget
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
pub(crate) struct TokenCheckRequest {
    pub pool: String,
    pub tokens: u64,
}

#[derive(Serialize)]
pub(crate) struct TokenCheckResponse {
    pub allowed: bool,
    pub available: u64,
}

#[derive(Deserialize)]
pub(crate) struct TokenReserveRequest {
    pub pool: String,
    pub tokens: u64,
}

#[derive(Serialize)]
pub(crate) struct TokenReserveResponse {
    pub reserved: bool,
    pub available: u64,
}

#[derive(Deserialize)]
pub(crate) struct TokenReportRequest {
    pub pool: String,
    pub reserved: u64,
    pub actual: u64,
}

#[derive(Serialize)]
pub(crate) struct TokenReportResponse {
    pub used: u64,
    pub available: u64,
}

// ---------------------------------------------------------------------------
// MCP tools
// ---------------------------------------------------------------------------

#[cfg(feature = "tools")]
#[derive(Deserialize)]
pub(crate) struct ToolCallRequest {
    pub name: String,
    #[serde(default)]
    pub arguments: serde_json::Value,
}

// ---------------------------------------------------------------------------
// Cost tracking
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct CostsResponse {
    pub records: Vec<crate::cost::ProviderCostRecord>,
    pub total_cost_usd: f64,
}

// ---------------------------------------------------------------------------
// Audit
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct AuditResponse {
    pub entries: Vec<crate::audit::AuditEntry>,
    pub total: usize,
    pub chain_valid: bool,
}

// ---------------------------------------------------------------------------
// Streaming budget guard
// ---------------------------------------------------------------------------

/// Drop guard that reports budget, cost, metrics, and events when a stream ends.
pub(crate) struct StreamBudgetGuard {
    pub state: Arc<AppState>,
    pub pool: String,
    pub estimated: u64,
    pub actual: Arc<std::sync::atomic::AtomicU64>,
    pub provider: String,
    pub model: String,
    pub start: std::time::Instant,
}

impl Drop for StreamBudgetGuard {
    fn drop(&mut self) {
        let actual = self.actual.load(std::sync::atomic::Ordering::Relaxed);
        let latency_ms = self.start.elapsed().as_millis() as u64;

        // Budget reporting
        match self.state.budget.try_lock() {
            Ok(mut budget) => budget.report(&self.pool, self.estimated, actual),
            Err(std::sync::TryLockError::Poisoned(e)) => {
                e.into_inner().report(&self.pool, self.estimated, actual);
            }
            Err(std::sync::TryLockError::WouldBlock) => {
                let state = self.state.clone();
                let pool = self.pool.clone();
                let estimated = self.estimated;
                tokio::spawn(async move {
                    let mut budget = state.budget.lock().unwrap_or_else(|e| e.into_inner());
                    budget.report(&pool, estimated, actual);
                });
            }
        }

        // Metrics
        crate::metrics::record_request(
            &self.provider,
            &self.model,
            "success",
            latency_ms as f64 / 1000.0,
            0,
            actual as u32,
        );

        // Event bus
        self.state.event_bus.publish(
            crate::events::topics::INFERENCE,
            crate::events::ProviderEvent::InferenceCompleted {
                provider: self.provider.clone(),
                model: self.model.clone(),
                latency_ms,
                tokens: actual as u32,
            },
        );
    }
}

// ---------------------------------------------------------------------------
// Hardware (hwaccel feature)
// ---------------------------------------------------------------------------

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct HardwareResponse {
    pub accelerators: Vec<AcceleratorInfo>,
    pub total_vram_bytes: u64,
    pub available_vram_bytes: u64,
    pub vram_reserve_bytes: u64,
    pub has_fast_interconnect: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<EnvironmentInfo>,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct AcceleratorInfo {
    pub name: String,
    pub family: String,
    pub memory_bytes: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_used_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_free_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub utilization_pct: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature_c: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub power_watts: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bandwidth_gbps: Option<f64>,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct EnvironmentInfo {
    pub is_docker: bool,
    pub is_kubernetes: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cloud_provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kubernetes_gpu: Option<KubernetesGpuInfo>,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct KubernetesGpuInfo {
    pub device_ids: Vec<String>,
    pub gpu_count: u32,
    pub source: String,
}

#[cfg(feature = "hwaccel")]
#[derive(Deserialize)]
pub(crate) struct PlacementRequest {
    pub model_params: u64,
    #[serde(default)]
    pub providers: Vec<String>,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct PlacementResponse {
    pub recommendation: crate::hardware::PlacementRecommendation,
    pub cloud_alternatives: Vec<CloudInstanceInfo>,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct CloudInstanceInfo {
    pub name: String,
    pub provider: String,
    pub gpu: String,
    pub gpu_count: u32,
    pub total_gpu_memory_gb: u32,
    pub price_per_hour: f64,
    pub memory_headroom_pct: f64,
}

// ---------------------------------------------------------------------------
// Model compatibility (hwaccel 1.2.0)
// ---------------------------------------------------------------------------

#[cfg(feature = "hwaccel")]
#[derive(Deserialize)]
pub(crate) struct ModelCompatRequest {
    /// Model name to look up (e.g. "Llama 3.1 70B").
    #[serde(default)]
    pub model: Option<String>,
    /// Quantization level (e.g. "Q4_K_M", "BFloat16"). Defaults to auto.
    #[serde(default)]
    pub quantization: Option<String>,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct ModelCompatResponse {
    /// Compatible models that fit on detected hardware.
    pub compatible: Vec<CompatibleModelInfo>,
    /// Total accelerator memory available.
    pub total_vram_bytes: u64,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct CompatibleModelInfo {
    pub name: String,
    pub family: String,
    pub params_billions: f64,
    pub memory_required_bytes: u64,
    pub headroom_pct: f64,
}

// ---------------------------------------------------------------------------
// What-if simulation (hwaccel 1.2.0)
// ---------------------------------------------------------------------------

#[cfg(feature = "hwaccel")]
#[derive(Deserialize)]
pub(crate) struct SimulateRequest {
    /// Devices to add (memory_bytes per device).
    #[serde(default)]
    pub add_devices: Vec<SimulatedDevice>,
    /// Number of current devices to remove (by index).
    #[serde(default)]
    pub remove_count: usize,
    /// Model parameter count to plan sharding for.
    pub model_params: u64,
}

#[cfg(feature = "hwaccel")]
#[derive(Deserialize)]
pub(crate) struct SimulatedDevice {
    pub memory_bytes: u64,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct SimulateResponse {
    pub original: SimulateSnapshot,
    pub simulated: SimulateSnapshot,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct SimulateSnapshot {
    pub device_count: usize,
    pub total_vram_bytes: u64,
    pub sharding: crate::hardware::ShardingSummary,
}

// ---------------------------------------------------------------------------
// Model format detection (hwaccel 1.2.0)
// ---------------------------------------------------------------------------

#[cfg(feature = "hwaccel")]
#[derive(Deserialize)]
pub(crate) struct ModelFormatRequest {
    /// Path to a local model file.
    pub path: String,
}

#[cfg(feature = "hwaccel")]
#[derive(Serialize)]
pub(crate) struct ModelFormatResponse {
    pub format: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub param_count: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dtype: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tensor_count: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format_version: Option<u32>,
}