wauldo 0.7.0

Official Rust SDK for Wauldo — Verified AI answers from your documents
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
//! HTTP API request/response types (OpenAI-compatible)

use serde::{Deserialize, Serialize};

// ── Chat Completions ────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct ChatRequest {
    pub model: String,
    pub messages: Vec<ChatMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    pub role: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatResponse {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<ChatChoice>,
    pub usage: Usage,
}

impl ChatResponse {
    /// Get the text content of the first choice (None if no content)
    pub fn text(&self) -> Option<&str> {
        self.choices
            .first()
            .and_then(|c| c.message.content.as_deref())
    }

    /// Get the text content or an empty string — convenience for display
    pub fn content(&self) -> String {
        self.text().unwrap_or("").to_string()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChoice {
    pub index: u32,
    pub message: ChatMessage,
    pub finish_reason: Option<String>,
}

// ── Streaming ───────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChunk {
    pub id: String,
    pub choices: Vec<ChatChunkChoice>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChunkChoice {
    pub delta: ChatDelta,
    pub finish_reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatDelta {
    pub content: Option<String>,
}

// ── Usage ───────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

// ── Models ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelList {
    pub object: String,
    pub data: Vec<Model>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Model {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub owned_by: String,
}

// ── Embeddings ──────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct EmbeddingRequest {
    pub input: EmbeddingInput,
    pub model: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum EmbeddingInput {
    Single(String),
    Multiple(Vec<String>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingResponse {
    pub data: Vec<EmbeddingData>,
    pub model: String,
    pub usage: EmbeddingUsage,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingData {
    pub embedding: Vec<f32>,
    pub index: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingUsage {
    pub prompt_tokens: u32,
    pub total_tokens: u32,
}

// ── RAG ─────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct RagUploadRequest {
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagUploadResponse {
    pub document_id: String,
    pub chunks_count: usize,
}

/// Quality assessment of an uploaded document
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentQuality {
    pub score: f32,
    pub label: String,
    pub word_count: usize,
    pub line_density: f32,
    pub avg_line_length: f32,
    pub paragraph_count: usize,
}

/// Response from POST /v1/upload-file (PDF, DOCX, text, image)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadFileResponse {
    pub document_id: String,
    pub chunks_count: usize,
    pub indexed_at: String,
    pub content_type: String,
    pub trace_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<DocumentQuality>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RagQueryRequest {
    pub query: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<usize>,
    /// Enable debug mode — returns retrieval funnel details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub debug: Option<bool>,
    /// Enable SSE streaming (sources → token* → audit → \[DONE\])
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    /// Quality mode: "fast", "balanced", "premium"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality_mode: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagQueryResponse {
    pub answer: String,
    pub sources: Vec<RagSource>,
    /// Full audit trail — always present
    #[serde(default)]
    pub audit: Option<RagAuditInfo>,
    // Legacy flat fields (servers < v1.6.5 may return these at root level)
    #[serde(default)]
    pub confidence: Option<f32>,
    #[serde(default)]
    pub grounded: Option<bool>,
}

impl RagQueryResponse {
    /// Get confidence from audit (preferred) or legacy flat field
    pub fn confidence(&self) -> Option<f32> {
        self.audit.as_ref().map(|a| a.confidence).or(self.confidence)
    }

    /// Get grounded from audit (preferred) or legacy flat field
    pub fn grounded(&self) -> Option<bool> {
        self.audit.as_ref().map(|a| a.grounded).or(self.grounded)
    }
}

/// Audit trail for RAG responses — verification and accountability
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagAuditInfo {
    pub confidence: f32,
    pub retrieval_path: String,
    pub sources_evaluated: usize,
    pub sources_used: usize,
    pub best_score: f32,
    pub grounded: bool,
    pub confidence_label: String,
    pub model: String,
    pub latency_ms: u64,
    /// Retrieval funnel diagnostics (v1.6.5+)
    #[serde(default)]
    pub candidates_found: Option<usize>,
    #[serde(default)]
    pub candidates_after_tenant: Option<usize>,
    #[serde(default)]
    pub candidates_after_score: Option<usize>,
    #[serde(default)]
    pub query_type: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagSource {
    pub document_id: String,
    pub content: String,
    pub score: f32,
    #[serde(default)]
    pub chunk_id: Option<String>,
    #[serde(default)]
    pub metadata: Option<serde_json::Value>,
}

// ── Orchestrator ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct OrchestratorRequest {
    pub prompt: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrchestratorResponse {
    pub final_output: String,
}

// ── Fact-Check ─────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct FactCheckRequest {
    pub text: String,
    pub source_context: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaimResult {
    pub text: String,
    pub claim_type: String,
    pub supported: bool,
    pub confidence: f64,
    pub confidence_label: String,
    pub verdict: String,
    pub action: String,
    #[serde(default)]
    pub reason: Option<String>,
    #[serde(default)]
    pub evidence: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FactCheckResponse {
    pub verdict: String,
    pub action: String,
    pub hallucination_rate: f64,
    pub mode: String,
    pub total_claims: usize,
    pub supported_claims: usize,
    pub confidence: f64,
    pub claims: Vec<ClaimResult>,
    #[serde(default)]
    pub mode_warning: Option<String>,
    pub processing_time_ms: u64,
}

impl FactCheckRequest {
    pub fn new(text: impl Into<String>, source_context: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            source_context: source_context.into(),
            mode: None,
        }
    }

    pub fn with_mode(mut self, mode: impl Into<String>) -> Self {
        self.mode = Some(mode.into());
        self
    }
}

// ── Citation Verify ──────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceChunk {
    pub name: String,
    pub content: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CitationDetail {
    pub citation: String,
    pub source_name: String,
    pub is_valid: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct VerifyCitationRequest {
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sources: Option<Vec<SourceChunk>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyCitationResponse {
    pub citation_ratio: f64,
    pub has_sufficient_citations: bool,
    pub sentence_count: usize,
    pub citation_count: usize,
    pub uncited_sentences: Vec<String>,
    #[serde(default)]
    pub citations: Option<Vec<CitationDetail>>,
    #[serde(default)]
    pub phantom_count: Option<usize>,
    pub processing_time_ms: u64,
}

impl VerifyCitationRequest {
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            sources: None,
            threshold: None,
        }
    }

    pub fn with_sources(mut self, sources: Vec<SourceChunk>) -> Self {
        self.sources = Some(sources);
        self
    }

    pub fn with_threshold(mut self, threshold: f64) -> Self {
        self.threshold = Some(threshold);
        self
    }
}

// ── Guard (Fact-Check) ─────────────────────────────────────────────────

/// Deprecated — use GuardResponse instead
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardResult {
    pub safe: bool,
    pub verdict: String,
    pub action: String,
    pub reason: Option<String>,
    pub confidence: f64,
}

#[derive(Debug, Clone, Serialize)]
pub struct GuardRequest {
    pub text: String,
    pub source_context: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
}

/// A single verified claim from the Guard response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardClaim {
    pub text: String,
    #[serde(default)]
    pub claim_type: Option<String>,
    pub supported: bool,
    pub confidence: f32,
    #[serde(default)]
    pub confidence_label: Option<String>,
    pub verdict: String,
    pub action: String,
    #[serde(default)]
    pub reason: Option<String>,
    #[serde(default)]
    pub evidence: Option<String>,
}

/// Response from POST /v1/fact-check — the Guard verification API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardResponse {
    pub verdict: String,
    pub action: String,
    pub hallucination_rate: f32,
    pub mode: String,
    pub total_claims: usize,
    pub supported_claims: usize,
    pub confidence: f32,
    pub claims: Vec<GuardClaim>,
    #[serde(default)]
    pub mode_warning: Option<String>,
    #[serde(default)]
    pub processing_time_ms: Option<u64>,
}

impl GuardResponse {
    /// True if the verdict allows the content through
    pub fn is_safe(&self) -> bool {
        self.verdict == "verified"
    }

    /// True if the content should be blocked
    pub fn is_blocked(&self) -> bool {
        self.action == "block"
    }
}

// ── Insights & Analytics ───────────────────────────────────────────────

/// GET /v1/insights response — ROI metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InsightsResponse {
    pub tig_key: String,
    pub total_requests: u64,
    pub intelligence_requests: u64,
    pub fallback_requests: u64,
    pub tokens: InsightsTokenStats,
    pub cost: InsightsCostStats,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InsightsTokenStats {
    pub baseline_total: u64,
    pub real_total: u64,
    pub saved_total: i64,
    pub saved_percent_avg: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InsightsCostStats {
    pub estimated_usd_saved: f64,
}

/// GET /v1/analytics response — usage analytics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsResponse {
    pub cache: CacheMetrics,
    pub tokens: TokenSavings,
    pub uptime_secs: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheMetrics {
    pub total_requests: u64,
    pub cache_hit_rate: f32,
    pub avg_latency_ms: f32,
    pub p95_latency_ms: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenSavings {
    pub total_baseline: u64,
    pub total_real: u64,
    pub total_saved: u64,
    pub avg_savings_percent: f32,
}

/// GET /v1/analytics/traffic response — per-tenant traffic
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrafficSummary {
    pub total_requests_today: u64,
    pub total_tokens_today: u64,
    pub top_tenants: Vec<TenantTraffic>,
    pub error_rate: f32,
    pub avg_latency_ms: u64,
    pub p95_latency_ms: u64,
    pub uptime_secs: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TenantTraffic {
    pub tenant_id: String,
    pub requests_today: u64,
    pub tokens_used: u64,
    pub success_rate: f32,
    pub avg_latency_ms: u64,
}

// ── Builders ────────────────────────────────────────────────────────────

impl ChatRequest {
    pub fn new(model: impl Into<String>, messages: Vec<ChatMessage>) -> Self {
        Self {
            model: model.into(),
            messages,
            temperature: None,
            max_tokens: None,
            stream: None,
            top_p: None,
            stop: None,
        }
    }

    /// Create a quick single-message chat request
    pub fn quick(model: impl Into<String>, message: impl Into<String>) -> Self {
        Self::new(model, vec![ChatMessage::user(message)])
    }
}

impl ChatMessage {
    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: "user".into(),
            content: Some(content.into()),
            name: None,
        }
    }

    pub fn system(content: impl Into<String>) -> Self {
        Self {
            role: "system".into(),
            content: Some(content.into()),
            name: None,
        }
    }

    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: "assistant".into(),
            content: Some(content.into()),
            name: None,
        }
    }
}