ariacompute-ffi 1.14.0

C ABI for Aria engine (cdylib/staticlib)
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
//! C ABI for Aria inference (chat / embeddings / ASR / tools).

#![allow(clippy::not_unsafe_ptr_arg_deref)] // C ABI: pointers are caller-owned
#![allow(clippy::too_many_arguments)]

use aria_inference::{ChatTurn, GenerateOpts, Session, SessionBuilder};
use serde_json::{json, Value};
use std::cell::RefCell;
use std::env;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_uchar, c_void};
use std::path::PathBuf;
use std::ptr;
use std::slice;

thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
    // Cache for strings returned to the caller as `const char *`. The pointer is
    // valid until the next call to a returning function on this thread.
    static LAST_STRING: RefCell<Option<CString>> = const { RefCell::new(None) };
}

/// Resolve the user-level Aria home (`~/.ariacompute`), overridable via
/// `ARIA_COMPUTE_HOME` (mirrors `openai/src/config.rs::aria_home`).
fn aria_home() -> Result<PathBuf, String> {
    if let Ok(override_home) = env::var("ARIA_COMPUTE_HOME") {
        if !override_home.is_empty() {
            return Ok(PathBuf::from(override_home));
        }
    }
    let home = if cfg!(windows) {
        env::var("USERPROFILE").map_err(|_| "could not resolve home directory".to_string())?
    } else {
        env::var("HOME").map_err(|_| "could not resolve home directory".to_string())?
    };
    Ok(PathBuf::from(home).join(".ariacompute"))
}

/// Return the on-disk cache directory for a model name:
/// `~/.ariacompute/models/{model}`. Overridable via `ARIA_COMPUTE_HOME`.
///
/// The returned `const char *` is owned by a thread-local cache and is valid
/// until the next call to a returning FFI function on this thread. Returns
/// `NULL` on error (inspect `aria_last_error`).
#[no_mangle]
pub extern "C" fn aria_model_cache_dir(model: *const c_char) -> *const c_char {
    clear_error();
    let model = match cstr_to_str(model) {
        Ok(m) => m,
        Err(e) => {
            set_error(e);
            return ptr::null();
        }
    };
    match aria_home() {
        Ok(home) => {
            let dir = home.join("models").join(model);
            let s = match CString::new(dir.to_string_lossy().as_bytes()) {
                Ok(s) => s,
                Err(e) => {
                    set_error(e.to_string());
                    return ptr::null();
                }
            };
            let ptr = s.as_ptr();
            LAST_STRING.with(|c| *c.borrow_mut() = Some(s));
            ptr
        }
        Err(e) => {
            set_error(e);
            ptr::null()
        }
    }
}

/// Whether `ref_` should be treated as a local bundle path rather than a model
/// name. A value containing a path separator or one that already exists on disk
/// is a local path.
#[no_mangle]
pub extern "C" fn aria_is_local_path(ref_: *const c_char) -> c_int {
    clear_error();
    let s = match cstr_to_str(ref_) {
        Ok(s) => s,
        Err(e) => {
            set_error(e);
            return -1;
        }
    };
    let is_local = s.contains('/') || s.contains('\\') || std::path::Path::new(s).exists();
    if is_local {
        1
    } else {
        0
    }
}

pub struct AriaModel {
    session: Session,
}

fn set_error(msg: impl Into<String>) {
    let s = CString::new(msg.into()).unwrap_or_else(|_| CString::new("error").unwrap());
    LAST_ERROR.with(|e| *e.borrow_mut() = Some(s));
}

fn clear_error() {
    LAST_ERROR.with(|e| *e.borrow_mut() = None);
}

fn cstr_to_str<'a>(p: *const c_char) -> Result<&'a str, String> {
    if p.is_null() {
        return Err("null string".into());
    }
    unsafe { CStr::from_ptr(p) }
        .to_str()
        .map_err(|e| e.to_string())
}

fn write_out(out: *mut c_char, out_len: usize, s: &str) -> c_int {
    if out.is_null() || out_len == 0 {
        set_error("null output buffer");
        return -1;
    }
    let bytes = s.as_bytes();
    if bytes.len() + 1 > out_len {
        set_error(format!(
            "output buffer too small: need {}, have {}",
            bytes.len() + 1,
            out_len
        ));
        return -1;
    }
    unsafe {
        ptr::copy_nonoverlapping(bytes.as_ptr(), out.cast::<u8>(), bytes.len());
        *out.add(bytes.len()) = 0;
    }
    0
}

fn parse_messages(messages_json: &str) -> Result<Vec<ChatTurn>, String> {
    let v: Value = serde_json::from_str(messages_json).map_err(|e| e.to_string())?;
    let arr = v
        .as_array()
        .ok_or_else(|| "messages must be a JSON array".to_string())?;
    let mut turns = Vec::new();
    for m in arr {
        let role = m
            .get("role")
            .and_then(|x| x.as_str())
            .unwrap_or("user")
            .to_string();
        let content = m
            .get("content")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();
        turns.push(ChatTurn { role, content });
    }
    Ok(turns)
}

fn parse_options(options_json: Option<&str>) -> GenerateOpts {
    let mut opts = GenerateOpts::default();
    if let Some(raw) = options_json {
        if let Ok(v) = serde_json::from_str::<Value>(raw) {
            if let Some(n) = v.get("max_tokens").and_then(|x| x.as_u64()) {
                opts.max_tokens = n as usize;
            }
            if let Some(t) = v.get("temperature").and_then(|x| x.as_f64()) {
                opts.temperature = t as f32;
            }
        }
    }
    if opts.max_tokens == 0 {
        opts.max_tokens = 16;
    }
    opts
}

fn parse_tools(tools_json: Option<&str>) -> Result<Value, String> {
    match tools_json {
        None | Some("") => Ok(json!([])),
        Some(raw) => {
            let v: Value = serde_json::from_str(raw).map_err(|e| e.to_string())?;
            if !v.is_array() && !v.is_null() {
                return Err("tools must be a JSON array or null".into());
            }
            Ok(if v.is_null() { json!([]) } else { v })
        }
    }
}

/// Opaque model handle.
pub type AriaModelHandle = *mut AriaModel;

/// Last error message (thread-local). Valid until next call on this thread.
#[no_mangle]
pub extern "C" fn aria_last_error() -> *const c_char {
    LAST_ERROR.with(|e| match e.borrow().as_ref() {
        Some(s) => s.as_ptr(),
        None => ptr::null(),
    })
}

/// Load an Aria quant bundle from `bundle_path`. Returns null on error.
#[no_mangle]
pub extern "C" fn aria_model_init(bundle_path: *const c_char) -> AriaModelHandle {
    clear_error();
    let path = match cstr_to_str(bundle_path) {
        Ok(p) => p,
        Err(e) => {
            set_error(e);
            return ptr::null_mut();
        }
    };
    match SessionBuilder::new().model(path).build() {
        Ok(session) => Box::into_raw(Box::new(AriaModel { session })),
        Err(e) => {
            set_error(e.to_string());
            ptr::null_mut()
        }
    }
}

/// Destroy a model handle. Safe on null. Double-destroy is undefined if caller reuses the pointer.
#[no_mangle]
pub extern "C" fn aria_model_destroy(model: AriaModelHandle) {
    clear_error();
    if model.is_null() {
        return;
    }
    unsafe {
        drop(Box::from_raw(model));
    }
}

fn complete_inner(
    model: AriaModelHandle,
    messages_json: *const c_char,
    options_json: *const c_char,
    tools_json: *const c_char,
    out: *mut c_char,
    out_len: usize,
    stream_cb: Option<unsafe extern "C" fn(*const c_char, *mut c_void)>,
    user_data: *mut c_void,
) -> c_int {
    clear_error();
    if model.is_null() {
        set_error("null model");
        return -1;
    }
    let messages = match cstr_to_str(messages_json) {
        Ok(s) => s,
        Err(e) => {
            set_error(e);
            return -1;
        }
    };
    let options = if options_json.is_null() {
        None
    } else {
        match cstr_to_str(options_json) {
            Ok(s) => Some(s),
            Err(e) => {
                set_error(e);
                return -1;
            }
        }
    };
    let tools_raw = if tools_json.is_null() {
        None
    } else {
        match cstr_to_str(tools_json) {
            Ok(s) => Some(s),
            Err(e) => {
                set_error(e);
                return -1;
            }
        }
    };

    let turns = match parse_messages(messages) {
        Ok(p) => p,
        Err(e) => {
            set_error(e);
            return -1;
        }
    };
    let tools = match parse_tools(tools_raw) {
        Ok(t) => t,
        Err(e) => {
            set_error(e);
            return -1;
        }
    };
    let opts = parse_options(options);
    let m = unsafe { &mut *model };
    let tokens = m.session.encode_chat(&turns);
    let gen = match m.session.generate(&tokens, &opts) {
        Ok(g) => g,
        Err(e) => {
            set_error(e.to_string());
            return -1;
        }
    };

    if let Some(cb) = stream_cb {
        // Stream decoded text (same as gen.text), not raw `<id>` placeholders.
        if let Ok(c) = CString::new(gen.text.as_str()) {
            unsafe { cb(c.as_ptr(), user_data) };
        }
    }

    let body = json!({
        "success": true,
        "error": null,
        "response": gen.text,
        "function_calls": json!([]),
        "segments": [],
        "cloud_handoff": false,
        "total_tokens": gen.tokens.len(),
    });
    // tools accepted for OpenAI parity; real tool routing is stage C.
    let _ = tools;
    write_out(out, out_len, &body.to_string())
}

/// Non-streaming chat completion. `tools_json` may be null.
#[no_mangle]
pub extern "C" fn aria_complete(
    model: AriaModelHandle,
    messages_json: *const c_char,
    options_json: *const c_char,
    tools_json: *const c_char,
    out: *mut c_char,
    out_len: usize,
) -> c_int {
    complete_inner(
        model,
        messages_json,
        options_json,
        tools_json,
        out,
        out_len,
        None,
        ptr::null_mut(),
    )
}

/// Streaming chat; `callback` receives each chunk as a C string.
#[no_mangle]
pub extern "C" fn aria_complete_stream(
    model: AriaModelHandle,
    messages_json: *const c_char,
    options_json: *const c_char,
    tools_json: *const c_char,
    out: *mut c_char,
    out_len: usize,
    callback: Option<unsafe extern "C" fn(*const c_char, *mut c_void)>,
    user_data: *mut c_void,
) -> c_int {
    complete_inner(
        model,
        messages_json,
        options_json,
        tools_json,
        out,
        out_len,
        callback,
        user_data,
    )
}

/// Embeddings. `input_json` is a string or `{"input":"..."}` / `{"input":[...]}`.
#[no_mangle]
pub extern "C" fn aria_embed(
    model: AriaModelHandle,
    input_json: *const c_char,
    out: *mut c_char,
    out_len: usize,
) -> c_int {
    clear_error();
    if model.is_null() {
        set_error("null model");
        return -1;
    }
    let raw = match cstr_to_str(input_json) {
        Ok(s) => s,
        Err(e) => {
            set_error(e);
            return -1;
        }
    };
    let text = match serde_json::from_str::<Value>(raw) {
        Ok(Value::String(s)) => s,
        Ok(v) => v
            .get("input")
            .and_then(|x| {
                x.as_str()
                    .map(|s| s.to_string())
                    .or_else(|| x.as_array().and_then(|a| a.first()).and_then(|x| x.as_str()).map(|s| s.to_string()))
            })
            .unwrap_or_default(),
        Err(_) => raw.to_string(),
    };
    if text.is_empty() {
        set_error("empty embedding input");
        return -1;
    }
    let m = unsafe { &*model };
    let emb = match m.session.embed_text(&text) {
        Ok(e) => e,
        Err(e) => {
            set_error(e.to_string());
            return -1;
        }
    };
    let body = json!({
        "object": "list",
        "data": [{
            "object": "embedding",
            "embedding": emb,
            "index": 0
        }]
    });
    write_out(out, out_len, &body.to_string())
}

/// Transcribe PCM16 LE bytes.
#[no_mangle]
pub extern "C" fn aria_transcribe(
    model: AriaModelHandle,
    pcm: *const c_uchar,
    pcm_len: usize,
    _options_json: *const c_char,
    out: *mut c_char,
    out_len: usize,
) -> c_int {
    clear_error();
    if model.is_null() {
        set_error("null model");
        return -1;
    }
    if pcm.is_null() || pcm_len == 0 {
        set_error("empty pcm");
        return -1;
    }
    let bytes = unsafe { slice::from_raw_parts(pcm, pcm_len) };
    let m = unsafe { &*model };
    let text = match m.session.transcribe_pcm16le(bytes) {
        Ok(t) => t,
        Err(e) => {
            set_error(e.to_string());
            return -1;
        }
    };
    let body = json!({
        "text": text,
        "segments": []
    });
    write_out(out, out_len, &body.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use aria_inference::fixture::write_tiny_q4_bundle;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn out_buf() -> Vec<u8> {
        vec![0u8; 64 * 1024]
    }

    #[test]
    fn init_complete_embed_transcribe_destroy() {
        let dir = tempfile::tempdir().unwrap();
        write_tiny_q4_bundle(dir.path()).unwrap();
        let path = CString::new(dir.path().to_str().unwrap()).unwrap();
        let model = aria_model_init(path.as_ptr());
        assert!(!model.is_null(), "{:?}", unsafe {
            CStr::from_ptr(aria_last_error()).to_string_lossy()
        });

        let messages = CString::new(r#"[{"role":"user","content":"hi"}]"#).unwrap();
        let options = CString::new(r#"{"max_tokens":2}"#).unwrap();
        let tools = CString::new("[]").unwrap();
        let mut buf = out_buf();
        assert_eq!(
            aria_complete(
                model,
                messages.as_ptr(),
                options.as_ptr(),
                tools.as_ptr(),
                buf.as_mut_ptr() as *mut c_char,
                buf.len(),
            ),
            0
        );
        let s = unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) }
            .to_str()
            .unwrap();
        let v: Value = serde_json::from_str(s).unwrap();
        assert_eq!(v["success"], true);
        assert!(!v["response"].as_str().unwrap().is_empty());

        let input = CString::new(r#"{"input":"hello"}"#).unwrap();
        buf.fill(0);
        assert_eq!(
            aria_embed(
                model,
                input.as_ptr(),
                buf.as_mut_ptr() as *mut c_char,
                buf.len()
            ),
            0
        );

        let pcm = [0u8, 1, 2, 3, 4, 5];
        buf.fill(0);
        assert_eq!(
            aria_transcribe(
                model,
                pcm.as_ptr(),
                pcm.len(),
                ptr::null(),
                buf.as_mut_ptr() as *mut c_char,
                buf.len()
            ),
            0
        );

        aria_model_destroy(model);
    }

    #[test]
    fn init_missing_path() {
        let path = CString::new("/no/such/bundle").unwrap();
        let model = aria_model_init(path.as_ptr());
        assert!(model.is_null());
        assert!(!aria_last_error().is_null());
    }

    #[test]
    fn complete_bad_json() {
        let dir = tempfile::tempdir().unwrap();
        write_tiny_q4_bundle(dir.path()).unwrap();
        let path = CString::new(dir.path().to_str().unwrap()).unwrap();
        let model = aria_model_init(path.as_ptr());
        let bad = CString::new("not-json").unwrap();
        let mut buf = out_buf();
        assert_ne!(
            aria_complete(
                model,
                bad.as_ptr(),
                ptr::null(),
                ptr::null(),
                buf.as_mut_ptr() as *mut c_char,
                buf.len()
            ),
            0
        );
        aria_model_destroy(model);
    }

    static CHUNKS: AtomicUsize = AtomicUsize::new(0);

    unsafe extern "C" fn on_chunk(_s: *const c_char, _ud: *mut c_void) {
        CHUNKS.fetch_add(1, Ordering::SeqCst);
    }

    #[test]
    fn complete_stream_ok() {
        let dir = tempfile::tempdir().unwrap();
        write_tiny_q4_bundle(dir.path()).unwrap();
        let path = CString::new(dir.path().to_str().unwrap()).unwrap();
        let model = aria_model_init(path.as_ptr());
        let messages = CString::new(r#"[{"role":"user","content":"hi"}]"#).unwrap();
        let options = CString::new(r#"{"max_tokens":2}"#).unwrap();
        let mut buf = out_buf();
        CHUNKS.store(0, Ordering::SeqCst);
        assert_eq!(
            aria_complete_stream(
                model,
                messages.as_ptr(),
                options.as_ptr(),
                ptr::null(),
                buf.as_mut_ptr() as *mut c_char,
                buf.len(),
                Some(on_chunk),
                ptr::null_mut(),
            ),
            0
        );
        assert!(CHUNKS.load(Ordering::SeqCst) >= 1);
        aria_model_destroy(model);
    }

    #[test]
    fn destroy_null_and_use_after_destroy() {
        aria_model_destroy(ptr::null_mut());
        let dir = tempfile::tempdir().unwrap();
        write_tiny_q4_bundle(dir.path()).unwrap();
        let path = CString::new(dir.path().to_str().unwrap()).unwrap();
        let model = aria_model_init(path.as_ptr());
        aria_model_destroy(model);
        let messages = CString::new(r#"[{"role":"user","content":"hi"}]"#).unwrap();
        let mut buf = out_buf();
        // After destroy the pointer must not be reused by callers; we only check null path.
        assert_ne!(
            aria_complete(
                ptr::null_mut(),
                messages.as_ptr(),
                ptr::null(),
                ptr::null(),
                buf.as_mut_ptr() as *mut c_char,
                buf.len()
            ),
            0
        );
    }

    #[test]
    fn cache_dir_uses_aria_compute_home() {
        let tmp = tempfile::tempdir().unwrap();
        std::env::set_var("ARIA_COMPUTE_HOME", tmp.path());
        let model = CString::new("gemma-4-e2b-it_q4").unwrap();
        let dir = aria_model_cache_dir(model.as_ptr());
        assert!(!dir.is_null());
        let s = unsafe { CStr::from_ptr(dir) }.to_str().unwrap();
        assert_eq!(
            s,
            tmp.path().join("models").join("gemma-4-e2b-it_q4").to_str().unwrap()
        );
        std::env::remove_var("ARIA_COMPUTE_HOME");
    }

    #[test]
    fn is_local_path_detects_separator_and_existing() {
        assert_eq!(aria_is_local_path(CString::new("/abs/path").unwrap().as_ptr()), 1);
        assert_eq!(aria_is_local_path(CString::new("C:\\win\\path").unwrap().as_ptr()), 1);
        assert_eq!(aria_is_local_path(CString::new("model_name").unwrap().as_ptr()), 0);
        // an existing path on disk is treated as local
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(
            aria_is_local_path(CString::new(tmp.path().to_str().unwrap()).unwrap().as_ptr()),
            1
        );
    }
}