prompty 2.0.0-alpha.8

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

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

/// Variant-specific data for [`Connection`], discriminated by `kind`.
#[derive(Debug, Clone)]
pub enum ConnectionKind {
    /// `kind` = `"reference"`
    Reference {
        /// The name of the connection
        name: String,
        /// The target resource or service that this connection refers to
        target: Option<String>,
    },
    /// `kind` = `"remote"`
    Remote {
        /// The name of the connection
        name: String,
        /// The endpoint URL for the AI service
        endpoint: String,
    },
    /// `kind` = `"key"`
    ApiKey {
        /// The endpoint URL for the AI service
        endpoint: String,
        /// The API key for authenticating with the AI service
        api_key: String,
    },
    /// `kind` = `"anonymous"`
    Anonymous {
        /// The endpoint for authenticating with the AI service
        endpoint: String,
    },
    /// `kind` = `"foundry"`
    Foundry {
        /// The Foundry project endpoint URL
        endpoint: String,
        /// The named connection within the Foundry project
        name: Option<String>,
        /// The connection type within the Foundry project (e.g., 'model', 'index', 'storage')
        connection_type: Option<String>,
    },
    /// `kind` = `"oauth"`
    OAuth {
        /// The endpoint URL for the service
        endpoint: String,
        /// The OAuth client ID
        client_id: String,
        /// The OAuth client secret
        client_secret: String,
        /// The OAuth token endpoint URL
        token_url: String,
        /// OAuth scopes to request
        scopes: Option<Vec<String>>,
    },
}

impl Default for ConnectionKind {
    fn default() -> Self {
        ConnectionKind::Reference {
            name: String::from(""),
            target: None,
        }
    }
}
/// Connection configuration for AI agents. `provider`, `kind`, and `endpoint` are required properties here, but this section can accept additional via options.
#[derive(Debug, Clone, Default)]
pub struct Connection {
    /// The authority level for the connection, indicating under whose authority the connection is made (e.g., 'user', 'agent', 'system')
    pub authentication_mode: Option<String>,
    /// The usage description for the connection, providing context on how this connection will be used
    pub usage_description: Option<String>,
    /// Variant-specific data, discriminated by `kind`.
    pub kind: ConnectionKind,
}

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

    /// Load Connection 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 Connection 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 Connection 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());
        let kind_str = value.get("kind").and_then(|v| v.as_str()).unwrap_or("");
        let kind = match kind_str {
            "reference" => ConnectionKind::Reference {
                name: value
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                target: value
                    .get("target")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
            },
            "remote" => ConnectionKind::Remote {
                name: value
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                endpoint: value
                    .get("endpoint")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
            },
            "key" => ConnectionKind::ApiKey {
                endpoint: value
                    .get("endpoint")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                api_key: value
                    .get("apiKey")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
            },
            "anonymous" => ConnectionKind::Anonymous {
                endpoint: value
                    .get("endpoint")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
            },
            "foundry" => ConnectionKind::Foundry {
                endpoint: value
                    .get("endpoint")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                name: value
                    .get("name")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
                connection_type: value
                    .get("connectionType")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
            },
            "oauth" => ConnectionKind::OAuth {
                endpoint: value
                    .get("endpoint")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                client_id: value
                    .get("clientId")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                client_secret: value
                    .get("clientSecret")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                token_url: value
                    .get("tokenUrl")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                scopes: value.get("scopes").and_then(|v| v.as_array()).map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                }),
            },
            _ => ConnectionKind::default(),
        };
        Self {
            authentication_mode: value
                .get("authenticationMode")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            usage_description: value
                .get("usageDescription")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            kind,
        }
    }

    /// Returns the `kind` discriminator string for this instance.
    pub fn kind_str(&self) -> &str {
        match &self.kind {
            ConnectionKind::Reference { .. } => "reference",
            ConnectionKind::Remote { .. } => "remote",
            ConnectionKind::ApiKey { .. } => "key",
            ConnectionKind::Anonymous { .. } => "anonymous",
            ConnectionKind::Foundry { .. } => "foundry",
            ConnectionKind::OAuth { .. } => "oauth",
        }
    }

    /// Serialize Connection 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 the discriminator
        result.insert(
            "kind".to_string(),
            serde_json::Value::String(self.kind_str().to_string()),
        );
        // Write base fields
        if let Some(ref val) = self.authentication_mode {
            result.insert(
                "authenticationMode".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if let Some(ref val) = self.usage_description {
            result.insert(
                "usageDescription".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        // Write variant-specific fields
        match &self.kind {
            ConnectionKind::Reference { name, target, .. } => {
                if !name.is_empty() {
                    result.insert("name".to_string(), serde_json::Value::String(name.clone()));
                }
                if let Some(val) = target {
                    result.insert("target".to_string(), serde_json::Value::String(val.clone()));
                }
            }
            ConnectionKind::Remote { name, endpoint, .. } => {
                if !name.is_empty() {
                    result.insert("name".to_string(), serde_json::Value::String(name.clone()));
                }
                if !endpoint.is_empty() {
                    result.insert(
                        "endpoint".to_string(),
                        serde_json::Value::String(endpoint.clone()),
                    );
                }
            }
            ConnectionKind::ApiKey {
                endpoint, api_key, ..
            } => {
                if !endpoint.is_empty() {
                    result.insert(
                        "endpoint".to_string(),
                        serde_json::Value::String(endpoint.clone()),
                    );
                }
                if !api_key.is_empty() {
                    result.insert(
                        "apiKey".to_string(),
                        serde_json::Value::String(api_key.clone()),
                    );
                }
            }
            ConnectionKind::Anonymous { endpoint, .. } => {
                if !endpoint.is_empty() {
                    result.insert(
                        "endpoint".to_string(),
                        serde_json::Value::String(endpoint.clone()),
                    );
                }
            }
            ConnectionKind::Foundry {
                endpoint,
                name,
                connection_type,
                ..
            } => {
                if !endpoint.is_empty() {
                    result.insert(
                        "endpoint".to_string(),
                        serde_json::Value::String(endpoint.clone()),
                    );
                }
                if let Some(val) = name {
                    result.insert("name".to_string(), serde_json::Value::String(val.clone()));
                }
                if let Some(val) = connection_type {
                    result.insert(
                        "connectionType".to_string(),
                        serde_json::Value::String(val.clone()),
                    );
                }
            }
            ConnectionKind::OAuth {
                endpoint,
                client_id,
                client_secret,
                token_url,
                scopes,
                ..
            } => {
                if !endpoint.is_empty() {
                    result.insert(
                        "endpoint".to_string(),
                        serde_json::Value::String(endpoint.clone()),
                    );
                }
                if !client_id.is_empty() {
                    result.insert(
                        "clientId".to_string(),
                        serde_json::Value::String(client_id.clone()),
                    );
                }
                if !client_secret.is_empty() {
                    result.insert(
                        "clientSecret".to_string(),
                        serde_json::Value::String(client_secret.clone()),
                    );
                }
                if !token_url.is_empty() {
                    result.insert(
                        "tokenUrl".to_string(),
                        serde_json::Value::String(token_url.clone()),
                    );
                }
                if let Some(items) = scopes {
                    result.insert(
                        "scopes".to_string(),
                        serde_json::to_value(items).unwrap_or(serde_json::Value::Null),
                    );
                }
            }
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

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