rig-core 0.47.0

An opinionated library for building LLM powered applications.
Documentation
//! Turn records: where each turn of a conversation began and how it ended,
//! kept as asides, so a saved session tells a stopped or failed turn from
//! an answered one without the app that ran it.

use std::fmt;

use serde::{Deserialize, Serialize};

use super::{Aside, AsideId, Author, CallRef, Conversation, MessageId};

/// The kind of an aside holding a [`TurnRecord`].
pub const TURN: &str = "rig.turn";

/// One turn of a conversation, from the message that asked for it to how
/// it ended. Kept as an aside of kind [`TURN`] by [`Author::rig`], put
/// after the last entry when the turn begins and replaced when it ends.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TurnRecord {
    /// How many turns began before this one.
    pub index: u64,
    /// Where it begins ([`Conversation::turn_start`]):
    /// [`asked`](Conversation::asked) is what it answers,
    /// [`request`](Conversation::request) the message that asked for it.
    pub start: MessageId,
    /// How it ended; `None` while it runs, when a crash cut it short, and
    /// when a plugin kept it running past an exit for the restart. An exit
    /// otherwise stops it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end: Option<TurnEnd>,
}

/// How a turn ended.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "how", rename_all = "snake_case")]
pub enum TurnEnd {
    /// The model answered.
    Answered {
        /// The reply entry the turn ended on; `None` when the last entry was
        /// no reply.
        #[serde(default, rename = "by", skip_serializing_if = "Option::is_none")]
        answer: Option<MessageId>,
    },
    /// The turn failed, for `why`.
    Failed {
        /// Why.
        why: String,
    },
    /// The turn was stopped before an answer, for `by`.
    Stopped {
        /// Who or what stopped it. `None` only in a record saved before
        /// the cause was recorded.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        by: Option<StopCause>,
        /// The turn's last entry when a stop cut it off, which a front draws
        /// the stop under; `None` when the turn had no entry of its own yet,
        /// or ended as stopped in its own course, such as a compaction
        /// ending it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        at: Option<MessageId>,
        /// The places of the tool calls the stop cut: those it answered,
        /// which had no result of their own, and those of the reply it cut
        /// off, which never ran and owe none. Empty in a record saved
        /// before calls had places.
        #[serde(default, rename = "cut", skip_serializing_if = "Vec::is_empty")]
        calls: Vec<CallRef>,
    },
}

/// Who or what stopped a turn before it answered.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopCause {
    /// The user stopped it.
    User,
    /// The app exited, for the reason given.
    Exit(String),
    /// A restart stopped the turn a crash left unfinished.
    Restarted,
    /// A plugin stopped it: `by` names the plugin, `why` says what for.
    Plugin {
        /// The plugin.
        by: String,
        /// What for.
        why: String,
    },
}

impl fmt::Display for StopCause {
    /// Why the turn stopped, as its unfinished calls are told.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::User => f.write_str("the user stopped the turn"),
            Self::Exit(why) | Self::Plugin { why, .. } => f.write_str(why),
            Self::Restarted => f.write_str("the session restarted"),
        }
    }
}

impl TurnRecord {
    /// The record `aside` holds, when it is one: of kind [`TURN`], its
    /// value a record.
    pub fn of(aside: &Aside) -> Option<Self> {
        aside.read(TURN)
    }
}

impl Conversation {
    /// The turn records, oldest first, with their asides' ids; the newest
    /// is `turns().next_back()`, found from the end.
    pub fn turns(&self) -> impl DoubleEndedIterator<Item = (AsideId, TurnRecord)> + '_ {
        self.asides()
            .filter_map(|(id, aside)| Some((id, TurnRecord::of(aside)?)))
    }

    /// Records a turn that begins now, numbered after the last record and
    /// starting at [`turn_start`](Self::turn_start). Returns the new record.
    pub fn open_turn(&mut self) -> TurnRecord {
        let last = self.turns().next_back().map(|(_, record)| record.index);
        let record = TurnRecord {
            index: last.map_or(0, |index| index.saturating_add(1)),
            start: self.turn_start(),
            end: None,
        };
        let after = self.entries().next_back().map(|entry| entry.id);
        let value = serde_json::to_value(&record).unwrap_or_default();
        self.add_aside(Aside::new(TURN, Author::rig(), value).after(after));
        record
    }

    /// Ends the last turn record, when it is open, with `end`. Returns
    /// whether it was open.
    pub fn end_turn(&mut self, end: TurnEnd) -> bool {
        let Some((id, record)) = self.turns().next_back() else {
            return false;
        };
        let Some(aside) = self.aside(id).filter(|_| record.end.is_none()).cloned() else {
            return false;
        };
        let ended = TurnRecord {
            end: Some(end),
            ..record
        };
        let value = serde_json::to_value(ended).unwrap_or_default();
        self.replace_aside(id, Aside { value, ..aside })
    }
}