use std::fmt;
use serde::{de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ToolDef {
#[serde(rename = "type")]
pub tool_type: String,
pub function: FunctionDef,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FunctionDef {
pub name: String,
pub description: String,
pub parameters: serde_json::Value,
pub strict: bool,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct FunctionCall {
pub id: String,
#[serde(rename = "type", alias = "type")]
pub tool_type: String,
pub function: FunctionCallInner,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct FunctionCallInner {
pub name: String,
#[serde(deserialize_with = "deserialize_arguments",serialize_with = "serialize_arguments")]
pub arguments: Value,
}
fn deserialize_arguments<'de, D>(deserializer: D) -> Result<Value, D::Error>
where
D: Deserializer<'de>,
{
struct ArgumentsVisitor;
impl<'de> Visitor<'de> for ArgumentsVisitor {
type Value = Value;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a JSON string or object representing the function arguments")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
serde_json::from_str(value)
.or_else(|_| Ok(Value::String(value.to_owned())))
.map_err(|e| de::Error::custom::<String>(e))
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
serde_json::from_str(&value)
.or_else(|_| Ok(Value::String(value)))
.map_err(|e| de::Error::custom::<String>(e))
}
fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
where
M: de::MapAccess<'de>,
{
Value::deserialize(de::value::MapAccessDeserializer::new(map))
}
}
deserializer.deserialize_any(ArgumentsVisitor)
}
fn serialize_arguments<S>(value: &Value, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = value.to_string();
serializer.serialize_str(&s)
}
pub trait Tool {
fn def_name(&self) -> &str;
fn def_description(&self) -> &str;
fn def_parameters(&self) -> serde_json::Value;
fn run(&self, args: serde_json::Value) -> Result<String, String>;
}