use crate::error::Result;
use crate::llm::broker::LlmBroker;
use crate::llm::models::{LlmMessage, MessageRole};
use crate::llm::tools::{FunctionDescriptor, LlmTool, ToolDescriptor};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
pub struct ToolWrapper {
broker: Arc<LlmBroker>,
tools: Vec<Box<dyn LlmTool>>,
behaviour: String,
name: String,
description: String,
}
impl ToolWrapper {
pub fn new(
broker: Arc<LlmBroker>,
tools: Vec<Box<dyn LlmTool>>,
behaviour: impl Into<String>,
name: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self {
broker,
tools,
behaviour: behaviour.into(),
name: name.into(),
description: description.into(),
}
}
fn create_initial_messages(&self) -> Vec<LlmMessage> {
vec![LlmMessage {
role: MessageRole::System,
content: Some(self.behaviour.clone()),
tool_calls: None,
image_paths: None,
reasoning_content: None,
}]
}
}
#[async_trait]
impl LlmTool for ToolWrapper {
async fn run(
&self,
args: &HashMap<String, Value>,
_ctx: &crate::llm::tools::ToolRunCtx,
) -> Result<Value> {
let input = args.get("input").and_then(|v| v.as_str()).ok_or_else(|| {
crate::error::MojenticError::ToolError("Missing 'input' parameter".to_string())
})?;
let mut messages = self.create_initial_messages();
messages.push(LlmMessage {
role: MessageRole::User,
content: Some(input.to_string()),
tool_calls: None,
image_paths: None,
reasoning_content: None,
});
let response = self.broker.generate(&messages, Some(&self.tools), None, None).await?;
Ok(json!(response))
}
fn descriptor(&self) -> ToolDescriptor {
ToolDescriptor {
r#type: "function".to_string(),
function: FunctionDescriptor {
name: self.name.clone(),
description: self.description.clone(),
parameters: json!({
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Instructions for this agent."
}
},
"required": ["input"],
"additionalProperties": false
}),
},
}
}
fn clone_box(&self) -> Box<dyn LlmTool> {
Box::new(ToolWrapper {
broker: self.broker.clone(),
tools: self.tools.iter().map(|t| t.clone_box()).collect(),
behaviour: self.behaviour.clone(),
name: self.name.clone(),
description: self.description.clone(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llm::gateway::{CompletionConfig, LlmGateway, StreamChunk};
use crate::llm::models::LlmGatewayResponse;
use futures::stream::{self, Stream};
use std::pin::Pin;
struct MockGateway {
expected_behaviour: String,
response: String,
}
impl MockGateway {
fn new(expected_behaviour: String, response: String) -> Self {
Self {
expected_behaviour,
response,
}
}
}
#[async_trait::async_trait]
impl LlmGateway for MockGateway {
async fn complete(
&self,
_model: &str,
messages: &[LlmMessage],
_tools: Option<&[Box<dyn LlmTool>]>,
_config: &CompletionConfig,
) -> Result<LlmGatewayResponse> {
assert!(messages.len() >= 2, "Expected at least 2 messages (system + user)");
assert_eq!(messages[0].role, MessageRole::System, "First message should be system");
assert_eq!(
messages[0].content.as_ref().unwrap(),
&self.expected_behaviour,
"System message should match behaviour"
);
Ok(LlmGatewayResponse {
content: Some(self.response.clone()),
object: None,
tool_calls: vec![],
thinking: None,
..Default::default()
})
}
async fn complete_json(
&self,
_model: &str,
_messages: &[LlmMessage],
_schema: Value,
_config: &CompletionConfig,
) -> Result<Value> {
Ok(json!({}))
}
async fn get_available_models(&self) -> Result<Vec<String>> {
Ok(vec![])
}
async fn calculate_embeddings(
&self,
_text: &str,
_model: Option<&str>,
) -> Result<Vec<f32>> {
Ok(vec![])
}
fn complete_stream<'a>(
&'a self,
_model: &'a str,
_messages: &'a [LlmMessage],
_tools: Option<&'a [Box<dyn LlmTool>]>,
_config: &'a CompletionConfig,
) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
Box::pin(stream::iter(vec![]))
}
}
#[tokio::test]
async fn test_tool_wrapper_descriptor() {
let gateway = Arc::new(MockGateway::new(
"You are a test agent".to_string(),
"test response".to_string(),
));
let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
let tools: Vec<Box<dyn LlmTool>> = vec![];
let wrapper = ToolWrapper::new(
broker,
tools,
"You are a test agent",
"test_agent",
"A test agent for unit testing",
);
let descriptor = wrapper.descriptor();
assert_eq!(descriptor.r#type, "function");
assert_eq!(descriptor.function.name, "test_agent");
assert_eq!(descriptor.function.description, "A test agent for unit testing");
let params = descriptor.function.parameters;
assert_eq!(params["type"], "object");
assert!(params["properties"]["input"].is_object());
assert_eq!(params["properties"]["input"]["type"], "string");
assert_eq!(params["properties"]["input"]["description"], "Instructions for this agent.");
assert_eq!(params["required"], json!(["input"]));
assert_eq!(params["additionalProperties"], false);
}
#[tokio::test]
async fn test_tool_wrapper_execution() {
let gateway = Arc::new(MockGateway::new(
"You are a helpful assistant".to_string(),
"I can help with that!".to_string(),
));
let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
let tools: Vec<Box<dyn LlmTool>> = vec![];
let wrapper = ToolWrapper::new(
broker,
tools,
"You are a helpful assistant",
"assistant",
"A helpful assistant",
);
let mut args = HashMap::new();
args.insert("input".to_string(), json!("Help me with something"));
let result = wrapper.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
assert_eq!(result, json!("I can help with that!"));
}
#[tokio::test]
async fn test_tool_wrapper_missing_input() {
let gateway =
Arc::new(MockGateway::new("You are a test agent".to_string(), "test".to_string()));
let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
let tools: Vec<Box<dyn LlmTool>> = vec![];
let wrapper =
ToolWrapper::new(broker, tools, "You are a test agent", "test_agent", "A test agent");
let args = HashMap::new();
let result = wrapper.run(&args, &crate::llm::tools::ToolRunCtx::default()).await;
assert!(result.is_err());
match result {
Err(crate::error::MojenticError::ToolError(message)) => {
assert_eq!(message, "Missing 'input' parameter");
}
_ => panic!("Expected ToolError"),
}
}
#[tokio::test]
async fn test_tool_wrapper_with_tools() {
struct MockTool;
#[async_trait]
impl LlmTool for MockTool {
async fn run(
&self,
_args: &HashMap<String, Value>,
_ctx: &crate::llm::tools::ToolRunCtx,
) -> Result<Value> {
Ok(json!({"result": "tool executed"}))
}
fn descriptor(&self) -> ToolDescriptor {
ToolDescriptor {
r#type: "function".to_string(),
function: FunctionDescriptor {
name: "mock_tool".to_string(),
description: "A mock tool".to_string(),
parameters: json!({}),
},
}
}
fn clone_box(&self) -> Box<dyn LlmTool> {
Box::new(MockTool)
}
}
let gateway = Arc::new(MockGateway::new(
"You are an agent with tools".to_string(),
"Task completed using tools".to_string(),
));
let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
let tools: Vec<Box<dyn LlmTool>> = vec![Box::new(MockTool)];
let wrapper = ToolWrapper::new(
broker,
tools,
"You are an agent with tools",
"tool_agent",
"An agent that has access to tools",
);
let mut args = HashMap::new();
args.insert("input".to_string(), json!("Use your tools"));
let result = wrapper.run(&args, &crate::llm::tools::ToolRunCtx::default()).await.unwrap();
assert_eq!(result, json!("Task completed using tools"));
}
#[tokio::test]
async fn test_tool_wrapper_matches() {
let gateway = Arc::new(MockGateway::new("test".to_string(), "test".to_string()));
let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
let tools: Vec<Box<dyn LlmTool>> = vec![];
let wrapper =
ToolWrapper::new(broker, tools, "You are a test agent", "my_agent", "A test agent");
assert!(wrapper.matches("my_agent"));
assert!(!wrapper.matches("other_agent"));
}
}