use kitchen_contract::{Format, Type};
use serde::{Deserialize, Serialize};
use crate::tool::TOOL_PROTOCOL;
use crate::tool::protocol::ToolRef;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolDescription {
pub name: String,
pub version: String,
pub tool_protocol: u32,
pub operations: Vec<Operation>,
}
impl ToolDescription {
pub fn compatible(&self) -> Result<(), String> {
match self.tool_protocol {
TOOL_PROTOCOL => Ok(()),
p if p > TOOL_PROTOCOL => Err(format!(
"{} speaks tool protocol {p}; this orchestrator speaks {TOOL_PROTOCOL}: update the orchestrator",
self.name
)),
p => Err(format!(
"{} speaks tool protocol {p}; this orchestrator speaks {TOOL_PROTOCOL}: update the tool",
self.name
)),
}
}
pub fn operation(&self, name: &str) -> Option<&Operation> {
self.operations.iter().find(|o| o.name == name)
}
pub fn tool_ref(&self) -> ToolRef {
ToolRef { name: self.name.clone(), version: self.version.clone(), image: None }
}
pub fn check(&self) -> Result<(), String> {
let mut seen = std::collections::BTreeSet::new();
for op in &self.operations {
if !seen.insert(op.name.as_str()) {
return Err(format!("{}: operation {} twice", self.name, op.name));
}
let mut ports = std::collections::BTreeSet::new();
for name in op.inputs.iter().map(|p| &p.name).chain(op.outputs.iter().map(|p| &p.name)) {
if !ports.insert(name.as_str()) {
return Err(format!("{}.{}: port {name} twice", self.name, op.name));
}
}
if op.outputs.is_empty() {
return Err(format!("{}.{}: no outputs", self.name, op.name));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Operation {
pub name: String,
pub summary: String,
pub inputs: Vec<InputPort>,
pub outputs: Vec<OutputPort>,
#[serde(default)]
pub recipe_schema: serde_json::Value,
#[serde(default)]
pub resources: Resources,
}
impl Operation {
pub fn input_for(&self, ty: &Type, format: &Format) -> Option<&InputPort> {
self.inputs.iter().find(|p| p.accepts(ty, format))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InputPort {
pub name: String,
#[serde(rename = "type")]
pub ty: Type,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub formats: Vec<Format>,
#[serde(default)]
pub many: bool,
#[serde(default)]
pub optional: bool,
}
impl InputPort {
pub fn accepts(&self, ty: &Type, format: &Format) -> bool {
ty.feeds(&self.ty) && (self.formats.is_empty() || self.formats.contains(format))
}
pub fn takes(&self) -> String {
if self.formats.is_empty() {
self.ty.to_string()
} else {
format!("{} in {}", self.ty, self.formats.iter().map(Format::as_str).collect::<Vec<_>>().join(" or "))
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OutputPort {
pub name: String,
#[serde(rename = "type")]
pub ty: Type,
pub format: Format,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Resources {
#[serde(default)]
pub gpu: bool,
#[serde(default)]
pub memory_gib: Option<f32>,
}