use alloc::{
boxed::Box,
format,
string::{String, ToString},
};
pub use llm_tool_macros::{llm_prompt, llm_resource, llm_tool};
pub use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::compat::HashMap;
const fn other_type_name(value: &serde_json::Value) -> &'static str {
match value {
serde_json::Value::Null => "null",
serde_json::Value::Bool(_) => "bool",
serde_json::Value::Number(_) => "number",
serde_json::Value::String(_) => "string",
serde_json::Value::Array(_) => "array",
serde_json::Value::Object(_) => "object",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolOutput {
pub(crate) content: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub(crate) metadata: HashMap<String, serde_json::Value>,
}
impl ToolOutput {
pub fn new(content: impl Into<String>) -> Self {
Self {
content: content.into(),
metadata: HashMap::new(),
}
}
pub fn json<T: serde::Serialize>(value: &T) -> Result<Self, ToolError> {
serde_json::to_string(value)
.map(Self::new)
.map_err(|e| ToolError::new(format!("serialization failed: {e}")))
}
pub fn from_metadata<T: serde::Serialize>(value: &T) -> Result<Self, ToolError> {
let json_value = serde_json::to_value(value)
.map_err(|e| ToolError::new(format!("metadata serialization failed: {e}")))?;
let content = json_value.to_string();
match json_value {
serde_json::Value::Object(map) => Ok(Self {
content,
metadata: map.into_iter().collect(),
}),
other => Err(ToolError::new(format!(
"metadata must serialize to a JSON object, got {}",
other_type_name(&other),
))),
}
}
#[must_use]
pub fn with_meta(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
self.metadata.insert(key.into(), value);
self
}
pub fn with_metadata<T: serde::Serialize>(mut self, value: &T) -> Result<Self, ToolError> {
let json = serde_json::to_value(value)
.map_err(|e| ToolError::new(format!("metadata serialization failed: {e}")))?;
match json {
serde_json::Value::Object(map) => {
self.metadata.extend(map);
Ok(self)
}
other => Err(ToolError::new(format!(
"metadata must serialize to a JSON object, got {}",
other_type_name(&other),
))),
}
}
#[must_use]
pub fn content(&self) -> &str {
&self.content
}
#[must_use]
pub fn into_content(self) -> String {
self.content
}
#[must_use]
pub const fn metadata(&self) -> &HashMap<String, serde_json::Value> {
&self.metadata
}
#[must_use]
pub fn truncated(mut self, policy: &TruncationPolicy) -> Self {
truncation::truncate_output(&mut self, policy);
self
}
pub fn truncate_detailed(
&mut self,
policy: &TruncationPolicy,
) -> Result<TruncationOutcome<'static>, SpillError> {
truncation::truncate_output_detailed(self, policy)
}
pub fn truncate_detailed_with_context(
&mut self,
policy: &TruncationPolicy,
ctx: &SpillContext<'_>,
) -> Result<TruncationOutcome<'static>, SpillError> {
truncation::truncate_output_detailed_with_context(self, policy, ctx)
}
}
impl core::fmt::Display for ToolOutput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.content)
}
}
impl From<String> for ToolOutput {
fn from(content: String) -> Self {
Self::new(content)
}
}
impl From<&str> for ToolOutput {
fn from(content: &str) -> Self {
Self::new(content)
}
}
impl From<i64> for ToolOutput {
fn from(value: i64) -> Self {
Self::new(value.to_string())
}
}
impl From<f64> for ToolOutput {
fn from(value: f64) -> Self {
Self::new(value.to_string())
}
}
impl From<bool> for ToolOutput {
fn from(value: bool) -> Self {
Self::new(value.to_string())
}
}
impl From<serde_json::Value> for ToolOutput {
fn from(value: serde_json::Value) -> Self {
Self::new(value.to_string())
}
}
pub struct Json<T>(pub T);
impl<T: serde::Serialize> From<Json<T>> for ToolOutput {
fn from(json: Json<T>) -> Self {
let json_value = serde_json::to_value(&json.0)
.expect("Json<T> serialization failed — this is a bug in the Serialize impl");
let content = json_value.to_string();
match json_value {
serde_json::Value::Object(map) => Self {
content,
metadata: map.into_iter().collect(),
},
_ => Self::new(content),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RegistryItem {
Tool,
Prompt,
Resource,
}
impl core::fmt::Display for RegistryItem {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Tool => write!(f, "tool"),
Self::Prompt => write!(f, "prompt"),
Self::Resource => write!(f, "resource"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolError {
pub message: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
metadata: HashMap<String, serde_json::Value>,
}
impl ToolError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
metadata: HashMap::new(),
}
}
pub const ERROR_KIND_KEY: &'static str = "error_kind";
pub const KIND_NOT_REGISTERED: &'static str = "not_registered";
pub const KIND_DESTRUCTIVE_BATCH: &'static str = "destructive_in_parallel_batch";
#[must_use]
pub fn not_found(kind: RegistryItem, name: &str) -> Self {
Self::new(format!("no {kind} named '{name}' is registered")).with_meta(
Self::ERROR_KIND_KEY,
serde_json::json!(Self::KIND_NOT_REGISTERED),
)
}
#[must_use]
pub fn destructive_in_parallel_batch(tool_name: &str) -> Self {
Self::new(format!(
"Tool '{tool_name}' has Destructive effect and cannot be executed in Parallel batch mode without explicit confirmation"
))
.with_meta(
Self::ERROR_KIND_KEY,
serde_json::json!(Self::KIND_DESTRUCTIVE_BATCH),
)
}
#[must_use]
pub fn with_meta(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
self.metadata.insert(key.into(), value);
self
}
pub fn with_metadata<T: serde::Serialize>(mut self, value: &T) -> Result<Self, Self> {
let json = match serde_json::to_value(value) {
Ok(j) => j,
Err(e) => {
self.message =
format!("{} (metadata serialization also failed: {e})", self.message);
return Err(self);
}
};
match json {
serde_json::Value::Object(map) => {
self.metadata.extend(map);
Ok(self)
}
other => {
self.message = format!(
"{} (metadata must serialize to a JSON object, got {})",
self.message,
other_type_name(&other),
);
Err(self)
}
}
}
#[must_use]
pub const fn metadata(&self) -> &HashMap<String, serde_json::Value> {
&self.metadata
}
#[must_use]
pub fn is_not_found(&self) -> bool {
self.metadata
.get(Self::ERROR_KIND_KEY)
.and_then(serde_json::Value::as_str)
== Some(Self::KIND_NOT_REGISTERED)
}
#[must_use]
pub fn is_destructive_batch_rejected(&self) -> bool {
self.metadata
.get(Self::ERROR_KIND_KEY)
.and_then(serde_json::Value::as_str)
== Some(Self::KIND_DESTRUCTIVE_BATCH)
}
}
impl core::fmt::Display for ToolError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.message)
}
}
impl core::error::Error for ToolError {}
impl From<String> for ToolError {
fn from(message: String) -> Self {
Self::new(message)
}
}
impl From<&str> for ToolError {
fn from(message: &str) -> Self {
Self::new(message)
}
}
#[cfg(feature = "std")]
impl From<std::io::Error> for ToolError {
fn from(e: std::io::Error) -> Self {
Self::new(e.to_string()).with_meta(
Self::ERROR_KIND_KEY,
serde_json::json!(format!("{:?}", e.kind())),
)
}
}
impl From<serde_json::Error> for ToolError {
fn from(e: serde_json::Error) -> Self {
Self::new(e.to_string())
.with_meta("category", serde_json::json!(format!("{:?}", e.classify())))
}
}
impl From<Box<dyn core::error::Error + Send + Sync>> for ToolError {
fn from(e: Box<dyn core::error::Error + Send + Sync>) -> Self {
Self::new(e.to_string())
}
}
impl From<core::convert::Infallible> for ToolError {
fn from(never: core::convert::Infallible) -> Self {
match never {}
}
}
pub mod context;
pub mod definition;
pub mod prompt;
pub mod quarantine;
pub mod resource;
pub mod sanitized;
pub mod truncation;
pub use context::*;
pub use definition::*;
pub use prompt::*;
pub use quarantine::*;
pub use resource::*;
pub use sanitized::*;
pub use truncation::*;
#[cfg(all(test, feature = "std"))]
mod tests;