use serde::{Deserialize, Serialize};
use crate::context::block::{BlockContent, ContextBlock};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ToolDefinition {
pub name: String,
pub description: String,
pub parameters: serde_json::Value,
}
impl ToolDefinition {
pub fn new(
name: impl Into<String>,
description: impl Into<String>,
parameters: serde_json::Value,
) -> Self {
Self {
name: name.into(),
description: description.into(),
parameters,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ToolChange {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub added: Vec<ToolDefinition>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub removed: Vec<String>,
}
impl ToolChange {
pub fn new(added: Vec<ToolDefinition>, removed: Vec<String>) -> Self {
Self { added, removed }
}
pub fn between(previous: &[ToolDefinition], current: &[ToolDefinition]) -> Self {
let find = |set: &[ToolDefinition], name: &str| {
set.iter()
.find(|definition| definition.name == name)
.cloned()
};
let added = current
.iter()
.filter(|definition| find(previous, &definition.name).as_ref() != Some(*definition))
.cloned()
.collect();
let removed = previous
.iter()
.filter(|definition| find(current, &definition.name).as_ref() != Some(*definition))
.map(|definition| definition.name.clone())
.collect();
Self { added, removed }
}
pub fn is_empty(&self) -> bool {
self.added.is_empty() && self.removed.is_empty()
}
pub fn apply_to(&self, tools: &mut Vec<ToolDefinition>) {
tools.retain(|definition| !self.removed.contains(&definition.name));
for definition in &self.added {
match tools
.iter_mut()
.find(|current| current.name == definition.name)
{
Some(current) => *current = definition.clone(),
None => tools.push(definition.clone()),
}
}
}
}
pub fn current_tools(blocks: &[ContextBlock]) -> Vec<ToolDefinition> {
let mut tools = Vec::new();
for block in blocks {
if let BlockContent::ToolChange(change) = block.content() {
change.apply_to(&mut tools);
}
}
tools
}