use std::ffi::c_void;
use std::fmt;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::time::Duration;
use antfly_embedded_sys::{
self as sys, antfly_buffer, antfly_error_code, antfly_inference, antfly_inference_options,
antfly_inference_pull_progress, antfly_slice,
};
use crate::db::{SUPPORTED_ABI_VERSION, abi_version};
use crate::error::Error;
use crate::ffi::{HandleGate, borrow_slice, check, path_to_bytes, take_buffer};
pub fn inference_options_size() -> u32 {
unsafe { sys::antfly_inference_options_size() }
}
fn compiled_inference_options_size() -> u32 {
std::mem::size_of::<antfly_inference_options>() as u32
}
fn validate_inference_abi() -> crate::Result<()> {
if abi_version() != SUPPORTED_ABI_VERSION {
return Err(Error::Internal);
}
if inference_options_size() != compiled_inference_options_size() {
return Err(Error::Internal);
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InferenceError {
pub error: Error,
pub body: String,
}
impl InferenceError {
fn new(error: Error, body: Vec<u8>) -> Self {
InferenceError {
error,
body: String::from_utf8_lossy(&body).into_owned(),
}
}
#[cfg(feature = "serde")]
pub fn message(&self) -> Option<String> {
let value: serde_json::Value = serde_json::from_str(&self.body).ok()?;
value.get("message")?.as_str().map(str::to_owned)
}
}
impl fmt::Display for InferenceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.body.is_empty() {
fmt::Display::fmt(&self.error, f)
} else {
write!(f, "{}: {}", self.error, self.body)
}
}
}
impl std::error::Error for InferenceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
pub type InferenceResult<T> = std::result::Result<T, InferenceError>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InferenceOptions {
pub models_dir: Option<PathBuf>,
pub host_budget_mb: u32,
pub backend_budget_mb: u32,
pub process_memory_budget_mb: u32,
pub combined_budget_mb: u32,
pub kv_budget_mb: u32,
pub scratch_budget_mb: u32,
pub call_timeout: Option<Duration>,
}
impl InferenceOptions {
pub fn new() -> Self {
Self::default()
}
pub fn models_dir(mut self, dir: impl AsRef<Path>) -> Self {
self.models_dir = Some(dir.as_ref().to_path_buf());
self
}
pub fn host_budget_mb(mut self, mb: u32) -> Self {
self.host_budget_mb = mb;
self
}
pub fn backend_budget_mb(mut self, mb: u32) -> Self {
self.backend_budget_mb = mb;
self
}
pub fn process_memory_budget_mb(mut self, mb: u32) -> Self {
self.process_memory_budget_mb = mb;
self
}
pub fn combined_budget_mb(mut self, mb: u32) -> Self {
self.combined_budget_mb = mb;
self
}
pub fn kv_budget_mb(mut self, mb: u32) -> Self {
self.kv_budget_mb = mb;
self
}
pub fn scratch_budget_mb(mut self, mb: u32) -> Self {
self.scratch_budget_mb = mb;
self
}
pub fn call_timeout(mut self, timeout: Duration) -> Self {
self.call_timeout = Some(timeout);
self
}
fn call_timeout_ms(&self) -> u64 {
match self.call_timeout {
Some(d) if !d.is_zero() => {
let ms = d.as_nanos().div_ceil(1_000_000);
u64::try_from(ms).unwrap_or(u64::MAX)
}
_ => 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullProgress {
pub model: String,
pub file: String,
pub bytes_downloaded: u64,
pub total_bytes: u64,
pub files_done: u64,
pub files_total: u64,
pub cached: bool,
}
impl PullProgress {
unsafe fn from_raw(raw: &antfly_inference_pull_progress) -> Self {
PullProgress {
model: unsafe { slice_to_string(raw.model) },
file: unsafe { slice_to_string(raw.file) },
bytes_downloaded: raw.bytes_downloaded,
total_bytes: raw.total_bytes,
files_done: raw.files_done,
files_total: raw.files_total,
cached: raw.cached,
}
}
}
unsafe fn slice_to_string(slice: antfly_slice) -> String {
if slice.ptr.is_null() || slice.len == 0 {
return String::new();
}
let bytes = unsafe { std::slice::from_raw_parts(slice.ptr, slice.len) };
String::from_utf8_lossy(bytes).into_owned()
}
pub struct Inference {
gate: HandleGate<antfly_inference>,
}
unsafe impl Send for Inference {}
unsafe impl Sync for Inference {}
impl Inference {
fn from_handle(handle: *mut antfly_inference) -> Inference {
Inference {
gate: HandleGate::new(handle),
}
}
fn with_handle<R>(
&self,
f: impl FnOnce(*mut antfly_inference) -> crate::Result<R>,
) -> crate::Result<R> {
self.gate.with_handle(f)
}
fn read_buffer(
&self,
f: impl FnOnce(*mut antfly_inference, *mut antfly_buffer) -> antfly_error_code,
) -> InferenceResult<Vec<u8>> {
let raw = self.with_handle(|handle| {
let mut out = antfly_buffer::default();
let code = f(handle, &mut out);
let body = unsafe { take_buffer(out) };
Ok((code, body))
});
finish(raw)
}
fn call_json(
&self,
request: &[u8],
f: impl FnOnce(*mut antfly_inference, antfly_slice, *mut antfly_buffer) -> antfly_error_code,
) -> InferenceResult<Vec<u8>> {
let raw = self.with_handle(|handle| {
let mut out = antfly_buffer::default();
let code = f(handle, borrow_slice(request), &mut out);
let body = unsafe { take_buffer(out) };
Ok((code, body))
});
finish(raw)
}
pub fn open(options: &InferenceOptions) -> crate::Result<Inference> {
validate_inference_abi()?;
let mut c_opts: antfly_inference_options = unsafe { std::mem::zeroed() };
check(unsafe { sys::antfly_inference_options_init(&mut c_opts) })?;
let models_dir_bytes = options.models_dir.as_deref().map(path_to_bytes);
if let Some(bytes) = &models_dir_bytes {
c_opts.models_dir = borrow_slice(bytes);
}
c_opts.host_budget_mb = options.host_budget_mb;
c_opts.backend_budget_mb = options.backend_budget_mb;
c_opts.process_memory_budget_mb = options.process_memory_budget_mb;
c_opts.combined_budget_mb = options.combined_budget_mb;
c_opts.kv_budget_mb = options.kv_budget_mb;
c_opts.scratch_budget_mb = options.scratch_budget_mb;
c_opts.call_timeout_ms = options.call_timeout_ms();
let mut handle: *mut antfly_inference = std::ptr::null_mut();
check(unsafe { sys::antfly_inference_open(&c_opts, &mut handle) })?;
Ok(Inference::from_handle(handle))
}
pub fn open_default() -> crate::Result<Inference> {
validate_inference_abi()?;
let mut handle: *mut antfly_inference = std::ptr::null_mut();
check(unsafe { sys::antfly_inference_open(std::ptr::null(), &mut handle) })?;
Ok(Inference::from_handle(handle))
}
pub fn close(&self) -> crate::Result<()> {
self.gate
.close(|handle| unsafe { sys::antfly_inference_close(handle) });
Ok(())
}
pub fn embed(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_embed_json(h, req, out)
})
}
pub fn rerank(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_rerank_json(h, req, out)
})
}
pub fn chunk(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_chunk_json(h, req, out)
})
}
pub fn generate(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_generate_json(h, req, out)
})
}
pub fn generate_stream(
&self,
request: impl AsRef<[u8]>,
on_chunk: &mut dyn FnMut(&[u8]) -> bool,
) -> InferenceResult<()> {
struct CallbackCtx<'a> {
on_chunk: &'a mut dyn FnMut(&[u8]) -> bool,
panic: Option<Box<dyn std::any::Any + Send>>,
}
unsafe extern "C" fn trampoline(ctx: *mut c_void, chunk_json: antfly_slice) -> bool {
if ctx.is_null() {
return true;
}
let ctx = unsafe { &mut *ctx.cast::<CallbackCtx>() };
if ctx.panic.is_some() {
return false;
}
let bytes: &[u8] = if chunk_json.ptr.is_null() || chunk_json.len == 0 {
&[]
} else {
unsafe { std::slice::from_raw_parts(chunk_json.ptr, chunk_json.len) }
};
let result = std::panic::catch_unwind(AssertUnwindSafe(|| (ctx.on_chunk)(bytes)));
match result {
Ok(cont) => cont,
Err(payload) => {
ctx.panic = Some(payload);
false
}
}
}
let raw = self.with_handle(|handle| {
let mut out = antfly_buffer::default();
let mut ctx = CallbackCtx {
on_chunk,
panic: None,
};
let ctx_ptr = std::ptr::addr_of_mut!(ctx).cast::<c_void>();
let code = unsafe {
sys::antfly_inference_generate_stream_json(
handle,
borrow_slice(request.as_ref()),
Some(trampoline),
ctx_ptr,
&mut out,
)
};
let body = unsafe { take_buffer(out) };
if let Some(payload) = ctx.panic.take() {
std::panic::resume_unwind(payload);
}
Ok((code, body))
});
match raw {
Ok((code, _body)) if code == sys::ANTFLY_OK => Ok(()),
Ok((code, body)) => Err(InferenceError::new(Error::from_code(code), body)),
Err(e) => Err(InferenceError::new(e, Vec::new())),
}
}
pub fn generate_batch(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_generate_batch_json(h, req, out)
})
}
pub fn rewrite(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_rewrite_json(h, req, out)
})
}
pub fn decide(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_decide_json(h, req, out)
})
}
pub fn extract(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_extract_json(h, req, out)
})
}
pub fn read(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
self.call_json(request.as_ref(), |h, req, out| unsafe {
sys::antfly_inference_read_json(h, req, out)
})
}
pub fn list_models(&self) -> InferenceResult<Vec<u8>> {
self.read_buffer(|h, out| unsafe { sys::antfly_inference_list_models_json(h, out) })
}
pub fn pull(
&self,
request: impl AsRef<[u8]>,
progress: Option<&mut dyn FnMut(&PullProgress) -> bool>,
) -> InferenceResult<Vec<u8>> {
struct CallbackCtx<'a> {
progress: &'a mut dyn FnMut(&PullProgress) -> bool,
panic: Option<Box<dyn std::any::Any + Send>>,
}
unsafe extern "C" fn trampoline(
ctx: *mut c_void,
raw: *const antfly_inference_pull_progress,
) -> bool {
if ctx.is_null() || raw.is_null() {
return true;
}
let ctx = unsafe { &mut *ctx.cast::<CallbackCtx>() };
if ctx.panic.is_some() {
return false;
}
let progress = unsafe { PullProgress::from_raw(&*raw) };
let result = std::panic::catch_unwind(AssertUnwindSafe(|| (ctx.progress)(&progress)));
match result {
Ok(cont) => cont,
Err(payload) => {
ctx.panic = Some(payload);
false
}
}
}
let raw = self.with_handle(|handle| {
let mut out = antfly_buffer::default();
let mut callback_ctx = progress.map(|f| CallbackCtx {
progress: f,
panic: None,
});
let (progress_fn, progress_ctx): (sys::antfly_inference_pull_progress_fn, *mut c_void) =
match callback_ctx.as_mut() {
Some(ctx) => (
Some(trampoline as _),
std::ptr::from_mut(ctx).cast::<c_void>(),
),
None => (None, std::ptr::null_mut()),
};
let code = unsafe {
sys::antfly_inference_pull_json(
handle,
borrow_slice(request.as_ref()),
progress_fn,
progress_ctx,
&mut out,
)
};
let body = unsafe { take_buffer(out) };
if let Some(ctx) = &mut callback_ctx
&& let Some(payload) = ctx.panic.take()
{
std::panic::resume_unwind(payload);
}
Ok((code, body))
});
finish(raw)
}
}
fn finish(raw: crate::Result<(antfly_error_code, Vec<u8>)>) -> InferenceResult<Vec<u8>> {
match raw {
Ok((code, body)) if code == sys::ANTFLY_OK => Ok(body),
Ok((code, body)) => Err(InferenceError::new(Error::from_code(code), body)),
Err(e) => Err(InferenceError::new(e, Vec::new())),
}
}
impl Drop for Inference {
fn drop(&mut self) {
let _ = self.close();
}
}
impl std::fmt::Debug for Inference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Inference")
.field("open", &self.gate.is_open())
.finish()
}
}