ailoy 0.3.3

Agents that drive a language model through tool-augmented turns, in a virtx console.
Documentation
use std::marker::PhantomData;

use serde::{Deserialize, Serialize};

use crate::{datatype::Value, message::Delta};

pub trait Marshal<T: ?Sized>: Default {
    fn marshal(&self, item: &T) -> Value;
}

pub trait Unmarshal<T: Delta>: Default {
    /// Parse a whole (non-streaming) response into `T`.
    fn unmarshal(&mut self, val: Value) -> anyhow::Result<T>;

    /// Parse one streaming (SSE) event's `data:` payload into a delta; events are shaped
    /// differently from the whole response. Control events (OpenAI `[DONE]`, Anthropic
    /// `ping`) return `Ok(None)`. Unsupported unless overridden.
    ///
    /// `&mut self` allows carrying state across a stream without `Arc`/`Mutex`.
    fn unmarshal_event(&mut self, _data: &str) -> anyhow::Result<Option<T>> {
        Err(anyhow::anyhow!(
            "streaming (SSE) is not supported for this provider"
        ))
    }
}

impl<T, M: Marshal<T>> Marshal<[T]> for M {
    fn marshal(&self, item: &[T]) -> Value {
        Value::Array(item.iter().map(|elem| self.marshal(elem)).collect())
    }
}

impl<T, M: Marshal<T>> Marshal<Vec<T>> for M {
    fn marshal(&self, item: &Vec<T>) -> Value {
        Value::Array(item.iter().map(|elem| self.marshal(elem)).collect())
    }
}

pub struct Marshaled<'d, D: ?Sized, M: Marshal<D>> {
    data: &'d D,
    m: PhantomData<M>,
}

impl<'d, D: ?Sized, M: Marshal<D>> Marshaled<'d, D, M> {
    pub fn new(data: &'d D) -> Self {
        Self {
            data,
            m: PhantomData,
        }
    }
}

impl<'d, D: ?Sized, M: Marshal<D>> Serialize for Marshaled<'d, D, M> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let v = M::default().marshal(self.data);
        v.serialize(serializer)
    }
}

impl<'d, D: ?Sized, M: Marshal<D>> From<Marshaled<'d, D, M>> for Value {
    fn from(marshaled: Marshaled<'d, D, M>) -> Self {
        M::default().marshal(marshaled.data)
    }
}

pub struct Unmarshaled<D: Delta, U: Unmarshal<D>> {
    data: D,
    u: std::marker::PhantomData<U>,
}

impl<D: Delta, U: Unmarshal<D>> Unmarshaled<D, U> {
    pub fn get(self) -> D {
        self.data
    }
}

impl<'de, D: Delta, U: Unmarshal<D>> Deserialize<'de> for Unmarshaled<D, U> {
    fn deserialize<De>(deserializer: De) -> Result<Self, De::Error>
    where
        De: serde::Deserializer<'de>,
    {
        let v = Value::deserialize(deserializer)?;
        let delta = U::default()
            .unmarshal(v)
            .map_err(|_| serde::de::Error::custom("Unable to decode"))?;
        Ok(Unmarshaled {
            data: delta,
            u: std::marker::PhantomData,
        })
    }
}