sermo 0.2.1

A Rust client library for interacting with various LLM provider APIs
Documentation
// Copyright 2025 Aquila Labs of Alberta, Canada <matt@cicero.sh>
// Licensed under either the Apache License, Version 2.0 OR the MIT License, at your option.
// You may not use this file except in compliance with one of the Licenses.
// Apache License text: https://www.apache.org/licenses/LICENSE-2.0
// MIT License text: https://opensource.org/licenses/MIT

use std::io;
use serde::{Serialize, Deserialize};
use serde_json::Value;

pub(crate) mod http;
pub mod web_search;
pub mod web_fetch;

/// Returns the string value of `key` in a JSON object, or an error if missing
/// or not a string.
pub(crate) fn arg_str<'a>(data: &'a Value, key: &str) -> Result<&'a str, io::Error> {
    data.get(key)
        .and_then(|v| v.as_str())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("Missing or invalid argument '{}'", key)))
}

/// Returns the unsigned integer value of `key`, or `default` if missing or not
/// a number.
pub(crate) fn arg_usize(data: &Value, key: &str, default: usize) -> usize {
    data.get(key).and_then(|v| v.as_u64()).map(|v| v as usize).unwrap_or(default)
}

/// Trait that all tools must implement
pub trait Tool {
    /// Returns the name of the tool
    fn name(&self) -> &str;

    /// Returns a description of what the tool does
    fn description(&self) -> &str;

    /// Executes the tool with the given JSON arguments
    fn execute(&self, arguments: &str) -> Result<String, io::Error>;
}

/// Represents a tool call request from the LLM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: String,
}

/// Represents the result of executing a tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    pub tool_call_id: String,
    pub content: String,
}

/// Tool definition for the LLM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    #[serde(rename = "type")]
    pub tool_type: String,
    pub function: FunctionDefinition,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionDefinition {
    pub name: String,
    pub description: String,
    pub parameters: serde_json::Value,
}

impl ToolDefinition {
    /// Creates a new tool definition from a Tool trait object
    pub fn from_tool<T: Tool + ?Sized>(tool: &T) -> Self {
        ToolDefinition {
            tool_type: "function".to_string(),
            function: FunctionDefinition {
                name: tool.name().to_string(),
                description: tool.description().to_string(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": []
                }),
            },
        }
    }
}