prompty 2.0.0-beta.1

Prompty is an asset class and format for LLM prompts
Documentation
// Code generated by Prompty emitter; DO NOT EDIT.

#![allow(
    unused_imports,
    dead_code,
    non_camel_case_types,
    unused_variables,
    clippy::all
)]

use super::super::context::{LoadContext, SaveContext};

use super::content_part::{ContentPart, ContentPartKind};

/// The result of a tool execution. Contains a list of content parts, enabling rich tool results (text, images, files, audio) rather than just strings. Implementations MUST support conversion from a plain string to a ToolResult containing a single TextPart for backward compatibility.
#[derive(Debug, Clone, Default)]
pub struct ToolResult {
    /// The content parts of the tool result
    pub parts: Vec<ContentPart>,
}

impl ToolResult {
    /// Create a new ToolResult with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load ToolResult from a JSON string.
    pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
        let value: serde_json::Value = serde_json::from_str(json)?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load ToolResult from a YAML string.
    pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
        let value: serde_json::Value = serde_yaml::from_str(yaml)?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load ToolResult from a `serde_json::Value`.
    ///
    /// Calls `ctx.process_input` before field extraction.
    pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
        let value = ctx.process_input(value.clone());
        Self {
            parts: value
                .get("parts")
                .map(|v| Self::load_parts(v, ctx))
                .unwrap_or_default(),
        }
    }

    /// Serialize ToolResult to a `serde_json::Value`.
    ///
    /// Calls `ctx.process_dict` after serialization.
    pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
        let mut result = serde_json::Map::new();
        // Write base fields
        if !self.parts.is_empty() {
            result.insert("parts".to_string(), Self::save_parts(&self.parts, ctx));
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize ToolResult to a JSON string.
    pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_value(ctx))
    }

    /// Serialize ToolResult to a YAML string.
    pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(&self.to_value(ctx))
    }

    /// Load a collection of ContentPart from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_parts(data: &serde_json::Value, ctx: &LoadContext) -> Vec<ContentPart> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| ContentPart::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of ContentPart to a JSON value.
    fn save_parts(items: &[ContentPart], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }
    /// Create a ToolResult with preset field values.
    pub fn text(value: impl Into<String>) -> Self {
        ToolResult {
            parts: vec![ContentPart {
                kind: ContentPartKind::TextPart {
                    value: value.into(),
                },
                ..Default::default()
            }],
            ..Default::default()
        }
    }
}
/// Helpers for [`ToolResult`]. Implement in a separate file.
pub trait ToolResultHelpers {
    /// Concatenate all TextPart values joined by newline
    fn text(&self) -> String;
}