use rig_core::message::{Message, ToolCall, UserContent};
use serde::{Deserialize, Serialize};
use super::calls::{ExecCall, MalformedCall, PendingToolCall};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) enum ToolSlot {
Execute(ToolCall),
Malformed(ToolCall),
Answered(UserContent),
}
impl ToolSlot {
pub(super) fn classify(tool_call: ToolCall, preresolved: Option<UserContent>) -> Self {
match preresolved {
Some(content) => Self::Answered(content),
None if tool_call.function.invalid_arguments.is_some() => Self::Malformed(tool_call),
None => Self::Execute(tool_call),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct ToolBatch {
pub(super) slots: Vec<ToolSlot>,
}
impl ToolBatch {
pub(super) fn pending(&self, turn: usize) -> Vec<PendingToolCall> {
self.slots
.iter()
.enumerate()
.filter_map(|(index, slot)| match slot {
ToolSlot::Execute(tool_call) => Some(PendingToolCall::Execute(ExecCall {
turn,
index,
tool_call: tool_call.clone(),
})),
ToolSlot::Malformed(tool_call) => Some(PendingToolCall::Malformed(MalformedCall {
turn,
index,
tool_call: tool_call.clone(),
})),
ToolSlot::Answered(_) => None,
})
.collect()
}
pub(super) fn complete(self) -> Result<Message, Self> {
if self
.slots
.iter()
.all(|slot| matches!(slot, ToolSlot::Answered(_)))
{
Ok(self.interrupt())
} else {
Err(self)
}
}
pub(super) fn interrupt(&self) -> Message {
let open = self.slots.iter().filter_map(|slot| match slot {
ToolSlot::Execute(tool_call) | ToolSlot::Malformed(tool_call) => Some(tool_call),
ToolSlot::Answered(_) => None,
});
let mut closed = match rig_core::conversation::pairing::close_pending(open) {
Message::User { content } => content.into_iter(),
_ => Vec::new().into_iter(),
};
let content = self
.slots
.iter()
.filter_map(|slot| match slot {
ToolSlot::Answered(content) => Some(content.clone()),
_ => closed.next(),
})
.collect();
Message::User { content }
}
}