Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(ai): move tools to new crate (#1009)

Eric Hayes9116ed6bb0d4
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index d7e9163d84..a306ff47d6 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -46,6 +46,7 @@ name = "ai"
version = "0.1.0"
dependencies = [
"ai_format",
+ "ai_toolset",
"anthropic",
"anyhow",
"async-openai",
@@ -87,6 +88,7 @@ version = "0.1.0"
dependencies = [
"ai",
"ai_format",
+ "ai_toolset",
"anthropic",
"anyhow",
"async-trait",
@@ -116,6 +118,20 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "ai_toolset"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "futures",
+ "schemars",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.17",
+ "utoipa",
+]
+
[[package]]
name = "aligned"
version = "0.4.2"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 11e9ad1b49..90100cbaaf 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -5,6 +5,7 @@ members = [
"ai",
"ai_format",
"ai_tools",
+ "ai_toolset",
"anthropic",
"authentication_service",
"authentication_service_client",
diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.toml
index e590874b58..b91a242423 100644
--- a/rust/cloud-storage/ai/Cargo.toml
+++ b/rust/cloud-storage/ai/Cargo.toml
@@ -29,6 +29,7 @@ tokio.workspace = true
tracing = { workspace = true }
utoipa = { workspace = true }
anthropic = { path = "../anthropic" }
+ai_toolset = { path = "../ai_toolset" }
base64 = { workspace = true }
image = "0.25.9"
webp = "0.3.1"
diff --git a/rust/cloud-storage/ai/src/lib.rs b/rust/cloud-storage/ai/src/lib.rs
index 83678566f8..f9ad9e7d2a 100644
--- a/rust/cloud-storage/ai/src/lib.rs
+++ b/rust/cloud-storage/ai/src/lib.rs
@@ -2,6 +2,7 @@ pub mod chat_completion;
pub mod chat_stream;
mod constants;
pub mod model_selection;
+mod openai_toolset;
pub mod simple_completion;
pub mod structured_output;
pub mod structured_output_v2;
@@ -10,3 +11,6 @@ pub mod tool;
pub mod traits;
pub mod types;
pub mod web_search;
+
+pub use ai_toolset::generate_tool_input_schema;
+pub use ai_toolset::generate_tool_output_schema;
diff --git a/rust/cloud-storage/ai/src/openai_toolset.rs b/rust/cloud-storage/ai/src/openai_toolset.rs
new file mode 100644
index 0000000000..351ee8ab9c
--- /dev/null
+++ b/rust/cloud-storage/ai/src/openai_toolset.rs
@@ -0,0 +1,38 @@
+//! OpenAI API integration for toolsets.
+//!
+//! This module provides conversions to OpenAI's tool types for use with
+//! the `async-openai` crate.
+
+use ai_toolset::ToolSet;
+use ai_toolset::tool_object::ToolObject;
+use async_openai::types::{ChatCompletionTool, ChatCompletionToolType, FunctionObject};
+
+/// Converts a ToolObject to an OpenAI ChatCompletionTool.
+pub fn tool_object_to_chat_completion_tool<T>(value: &ToolObject<T>) -> ChatCompletionTool {
+ ChatCompletionTool {
+ r#type: ChatCompletionToolType::Function,
+ function: FunctionObject {
+ name: value.name.clone(),
+ description: Some(value.description.clone()),
+ parameters: Some(value.input_schema.clone()),
+ strict: Some(true),
+ },
+ }
+}
+
+/// Extension trait for ToolSet to convert to OpenAI chat completion tools.
+pub trait OpenAIToolSetExt {
+ /// Converts this toolset to a vector of OpenAI chat completion tools.
+ ///
+ /// Returns tool definitions suitable for use with OpenAI's function calling API.
+ fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTool>;
+}
+
+impl<T> OpenAIToolSetExt for ToolSet<ToolObject<T>> {
+ fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTool> {
+ self.tools
+ .values()
+ .map(tool_object_to_chat_completion_tool)
+ .collect()
+ }
+}
diff --git a/rust/cloud-storage/ai/src/tool/completion.rs b/rust/cloud-storage/ai/src/tool/completion.rs
index a2a283ad2d..3783436fab 100644
--- a/rust/cloud-storage/ai/src/tool/completion.rs
+++ b/rust/cloud-storage/ai/src/tool/completion.rs
@@ -1,10 +1,9 @@
use super::types::ToolCall;
use super::types::tool_object::ToolObject;
+use crate::openai_toolset::tool_object_to_chat_completion_tool;
use crate::types::{AiError, Result};
use crate::types::{ChatCompletionRequest, OpenRouterClient};
-use async_openai::types::{
- ChatCompletionTool, ChatCompletionToolChoiceOption, CreateChatCompletionRequest,
-};
+use async_openai::types::{ChatCompletionToolChoiceOption, CreateChatCompletionRequest};
#[tracing::instrument(skip(tool))]
pub async fn tool_completion<T>(
@@ -12,7 +11,7 @@ pub async fn tool_completion<T>(
tool: &ToolObject<T>,
) -> Result<ToolCall> {
let mut request: CreateChatCompletionRequest = request.try_into()?;
- request.tools = Some(vec![ChatCompletionTool::from(tool)]);
+ request.tools = Some(vec![tool_object_to_chat_completion_tool(tool)]);
request.n = Some(1);
request.tool_choice = Some(ChatCompletionToolChoiceOption::Required);
diff --git a/rust/cloud-storage/ai/src/tool/mod.rs b/rust/cloud-storage/ai/src/tool/mod.rs
index 0b492b7796..473fd6f37a 100644
--- a/rust/cloud-storage/ai/src/tool/mod.rs
+++ b/rust/cloud-storage/ai/src/tool/mod.rs
@@ -2,6 +2,8 @@ pub mod completion;
pub mod tool_loop;
pub mod types;
+pub use ai_toolset::generate_tool_input_schema;
+pub use ai_toolset::generate_tool_output_schema;
pub use tool_loop::ai_client::ToolLoop;
pub use types::tool_object::minimized_output_schema_generator;
pub use types::*;
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
index 1c915a6d5d..2a34d4542a 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
@@ -1,4 +1,5 @@
use super::constant::MAX_RECURSIONS;
+use crate::openai_toolset::OpenAIToolSetExt;
use crate::tool::types::{AsyncToolSet, PartialToolCall, StreamPart, ToolCall, ToolResult};
use crate::tool::types::{ChatCompletionStream, ExtendedPartStream, PartOrExt, ToolResponse};
use crate::types::openai::message::convert_message;
diff --git a/rust/cloud-storage/ai/src/tool/types/mod.rs b/rust/cloud-storage/ai/src/tool/types/mod.rs
index 4723c98024..493ea28d5e 100644
--- a/rust/cloud-storage/ai/src/tool/types/mod.rs
+++ b/rust/cloud-storage/ai/src/tool/types/mod.rs
@@ -1,8 +1,6 @@
-pub mod schema;
mod stream;
-mod tool;
-mod toolset;
+pub use ai_toolset::schema;
+pub use ai_toolset::tool_object;
+pub use ai_toolset::*;
pub use stream::*;
-pub use tool::*;
-pub use toolset::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/schema/mod.rs b/rust/cloud-storage/ai/src/tool/types/schema/mod.rs
deleted file mode 100644
index 884ad437d2..0000000000
--- a/rust/cloud-storage/ai/src/tool/types/schema/mod.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-mod generate;
-mod phantom_tool;
-
-pub use generate::*;
-pub use phantom_tool::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/tool.rs b/rust/cloud-storage/ai/src/tool/types/tool.rs
deleted file mode 100644
index 571b0a74b3..0000000000
--- a/rust/cloud-storage/ai/src/tool/types/tool.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-use async_trait::async_trait;
-use serde::Serialize;
-
-pub type ToolResult<T> = std::result::Result<T, ToolCallError>;
-pub struct NoContext();
-
-#[derive(Debug)]
-pub struct ToolCallError {
- pub internal_error: anyhow::Error,
- pub description: String,
-}
-
-impl std::fmt::Display for ToolCallError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "description: {}. error: {}",
- self.description, self.internal_error
- )
- }
-}
-
-pub trait Tool<Sc, Rc>: Sync + Send {
- type Output: Serialize + 'static;
- fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output>;
-}
-
-#[async_trait]
-pub trait AsyncTool<Sc, Rc>: Sync + Send {
- type Output: Serialize + 'static;
- async fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output>;
-}
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/mod.rs b/rust/cloud-storage/ai/src/tool/types/toolset/mod.rs
deleted file mode 100644
index e8d782a1d7..0000000000
--- a/rust/cloud-storage/ai/src/tool/types/toolset/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub mod tool_object;
-mod types;
-pub use types::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/mod.rs b/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/mod.rs
deleted file mode 100644
index 0767418f5a..0000000000
--- a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/mod.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-#[macro_use]
-mod util;
-
-mod json_tool;
-mod object;
-mod tool;
-mod tool_async;
-
-pub use json_tool::*;
-pub use object::*;
-pub use tool::*;
-pub use tool_async::*;
-pub use util::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/object.rs b/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/object.rs
deleted file mode 100644
index 67d888f8c3..0000000000
--- a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/object.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use serde_json::Error as JsonError;
-use serde_json::Value;
-use thiserror::Error;
-
-pub struct ToolObject<T> {
- pub input_schema: Value,
- pub output_schema: Value,
- pub description: String,
- pub name: String,
- pub deserializer: T,
-}
-
-#[derive(Debug, Error)]
-pub enum ValidationError {
- #[error("missing metadata")]
- MissingMetadata,
- #[error("could not convert to json")]
- JsonSerialization(JsonError),
- #[error("schema exceeds depth one - nested objects with properties are not allowed")]
- ExceedsDepthOne,
- #[error("title is empty")]
- EmptyTitle,
- #[error("schema must not have oneOf set. Do not use descriptions or /// on enum types.")]
- OneOf,
-}
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index cbc1ad52cc..ad71718488 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dependencies]
ai = { path = "../ai" }
+ai_toolset = { path = "../ai_toolset" }
anyhow.workspace = true
async-trait.workspace = true
chrono.workspace = true
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 01f6880131..9b0266da0e 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -1,5 +1,5 @@
-use ai::tool::AsyncToolSet;
-use ai::tool::schema::{ToolSchemaGenerator, ToolSchemas};
+use ai_toolset::AsyncToolSet;
+use ai_toolset::schema::{ToolSchemaGenerator, ToolSchemas};
pub mod list;
pub mod prompts;
pub mod read;
@@ -23,7 +23,7 @@ pub struct ToolSetWithPrompt {
}
impl ToolSchemaGenerator for ToolSetWithPrompt {
- fn generate_schemas(&self) -> ai::tool::schema::ToolSchemas {
+ fn generate_schemas(&self) -> ai_toolset::schema::ToolSchemas {
self.toolset.generate_schemas()
}
}
@@ -44,7 +44,7 @@ pub fn all_tools() -> ToolSetWithPrompt {
}
/// These are used to generate schemas for the frontend
-/// See [ai::tool::types::schema::PhantomTool]
+/// See [ai_toolset::schema::PhantomTool]
pub fn all_tool_schemas() -> ToolSchemas {
all_tools()
.merge(&*anthropic_web_search_tool)
diff --git a/rust/cloud-storage/ai_tools/src/list/channel/test.rs b/rust/cloud-storage/ai_tools/src/list/channel/test.rs
index 8e84b0cfd5..56ffa57767 100644
--- a/rust/cloud-storage/ai_tools/src/list/channel/test.rs
+++ b/rust/cloud-storage/ai_tools/src/list/channel/test.rs
@@ -1,6 +1,6 @@
use super::*;
-use ai::generate_tool_input_schema;
-use ai::tool::types::tool_object::validate_tool_schema;
+use ai_toolset::generate_tool_input_schema;
+use ai_toolset::tool_object::validate_tool_schema;
#[test]
fn test_list_channels_schema_validation() {
@@ -32,7 +32,7 @@ fn print_input_schema() {
#[test]
#[ignore = "prints the output schema"]
fn print_output_schema() {
- let generator = ai::tool::minimized_output_schema_generator();
+ let generator = ai_toolset::tool_object::minimized_output_schema_generator();
let schema = generator.into_root_schema_for::<ListChannelsResponse>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
diff --git a/rust/cloud-storage/ai_tools/src/list/channel/tool.rs b/rust/cloud-storage/ai_tools/src/list/channel/tool.rs
index a061a9ce01..4c337d3908 100644
--- a/rust/cloud-storage/ai_tools/src/list/channel/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/list/channel/tool.rs
@@ -1,5 +1,5 @@
use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
use model::comms::ChannelType;
use schemars::JsonSchema;
diff --git a/rust/cloud-storage/ai_tools/src/list/email/tests.rs b/rust/cloud-storage/ai_tools/src/list/email/tests.rs
index 0ab12b4f1d..b03706f726 100644
--- a/rust/cloud-storage/ai_tools/src/list/email/tests.rs
+++ b/rust/cloud-storage/ai_tools/src/list/email/tests.rs
@@ -1,6 +1,6 @@
use super::tool::*;
-use ai::generate_tool_input_schema;
-use ai::tool::types::tool_object::validate_tool_schema;
+use ai_toolset::generate_tool_input_schema;
+use ai_toolset::tool_object::validate_tool_schema;
use cool_asserts::assert_matches;
use email::inbound::ApiPaginatedThreadCursor;
use models_email::service::thread::PreviewViewStandardLabel;
@@ -17,7 +17,7 @@ fn print_input_schema() {
#[test]
#[ignore = "prints the output schema"]
fn print_output_schema() {
- let generator = ai::tool::minimized_output_schema_generator();
+ let generator = ai_toolset::tool_object::minimized_output_schema_generator();
let schema = generator.into_root_schema_for::<ApiPaginatedThreadCursor>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
diff --git a/rust/cloud-storage/ai_tools/src/list/email/tool.rs b/rust/cloud-storage/ai_tools/src/list/email/tool.rs
index c0cc08d420..c4373e5f9e 100644
--- a/rust/cloud-storage/ai_tools/src/list/email/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/list/email/tool.rs
@@ -1,5 +1,5 @@
use crate::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
use email::inbound::ApiPaginatedThreadCursor;
use models_email::{
diff --git a/rust/cloud-storage/ai_tools/src/list/file.rs b/rust/cloud-storage/ai_tools/src/list/file.rs
index 2a8cb8e979..0bb171a608 100644
--- a/rust/cloud-storage/ai_tools/src/list/file.rs
+++ b/rust/cloud-storage/ai_tools/src/list/file.rs
@@ -1,5 +1,5 @@
use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
use model::document::list::DocumentListItem;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -244,8 +244,8 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ListDocuments {
#[cfg(test)]
mod tests {
use super::*;
- use ai::generate_tool_input_schema;
- use ai::tool::types::tool_object::validate_tool_schema;
+ use ai_toolset::generate_tool_input_schema;
+ use ai_toolset::tool_object::validate_tool_schema;
// run `cargo test -p ai_tools list::file::tests::print_input_schema -- --nocapture --include-ignored`
#[test]
@@ -259,7 +259,7 @@ mod tests {
#[test]
#[ignore = "prints the output schema"]
fn print_output_schema() {
- let generator = ai::tool::minimized_output_schema_generator();
+ let generator = ai_toolset::tool_object::minimized_output_schema_generator();
let schema = generator.into_root_schema_for::<ListDocumentsResponse>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
diff --git a/rust/cloud-storage/ai_tools/src/list/mod.rs b/rust/cloud-storage/ai_tools/src/list/mod.rs
index 7e2dc7fe87..e9904c895a 100644
--- a/rust/cloud-storage/ai_tools/src/list/mod.rs
+++ b/rust/cloud-storage/ai_tools/src/list/mod.rs
@@ -1,5 +1,5 @@
use crate::AiToolSet;
-use ai::tool::AsyncToolSet;
+use ai_toolset::AsyncToolSet;
mod channel;
mod email;
mod file;
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
index 8e4a82c1e8..8cb73b3db8 100644
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ b/rust/cloud-storage/ai_tools/src/read.rs
@@ -1,5 +1,5 @@
use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use anyhow::anyhow;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -472,8 +472,8 @@ impl Read {
#[cfg(test)]
mod tests {
use super::*;
- use ai::tool::types::tool_object::validate_tool_schema;
- use ai::{generate_tool_input_schema, generate_tool_output_schema};
+ use ai_toolset::tool_object::validate_tool_schema;
+ use ai_toolset::{generate_tool_input_schema, generate_tool_output_schema};
// run `cargo test -p ai_tools read::tests::print_input_schema -- --nocapture --include-ignored`
#[test]
diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
index af7cebb120..02cc7e3de1 100644
--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
@@ -1,9 +1,9 @@
use super::types::AIDiffResponse;
use super::types::{PROMPT, REWRITE_MODEL};
use crate::tool_context::{RequestContext, ToolScribe, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
use ai::types::{MessageBuilder, RequestBuilder};
use ai_format::document::Document;
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use anyhow::Error;
use async_trait::async_trait;
use model::document::FileType;
diff --git a/rust/cloud-storage/ai_tools/src/search/mod.rs b/rust/cloud-storage/ai_tools/src/search/mod.rs
index ad5ba28174..c6af884dd6 100644
--- a/rust/cloud-storage/ai_tools/src/search/mod.rs
+++ b/rust/cloud-storage/ai_tools/src/search/mod.rs
@@ -1,5 +1,5 @@
use crate::AiToolSet;
-use ai::tool::AsyncToolSet;
+use ai_toolset::AsyncToolSet;
mod search_service;
pub mod web;
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
index 767b742549..4e52725aef 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
@@ -1,6 +1,6 @@
use super::types::{PAGE_SIZE, SearchToolResponse};
use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
use models_search::{
MatchType,
@@ -76,8 +76,8 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ContentSearch {
#[cfg(test)]
mod tests {
use super::*;
- use ai::generate_tool_input_schema;
- use ai::tool::types::tool_object::validate_tool_schema;
+ use ai_toolset::generate_tool_input_schema;
+ use ai_toolset::tool_object::validate_tool_schema;
#[test]
fn test_content_search_schema_validation() {
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
index e7654fdd2f..53af7a08fe 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
@@ -1,6 +1,6 @@
use super::types::{PAGE_SIZE, SearchToolResponse};
use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
use models_search::{
MatchType,
@@ -76,8 +76,8 @@ impl AsyncTool<ToolServiceContext, RequestContext> for NameSearch {
#[cfg(test)]
mod tests {
use super::*;
- use ai::generate_tool_input_schema;
- use ai::tool::types::tool_object::validate_tool_schema;
+ use ai_toolset::generate_tool_input_schema;
+ use ai_toolset::tool_object::validate_tool_schema;
#[test]
fn test_name_search_schema_validation() {
diff --git a/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs b/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs
index e8832da75f..9ac8404827 100644
--- a/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs
+++ b/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs
@@ -1,4 +1,4 @@
-use ai::tool::schema::PhantomTool;
+use ai_toolset::schema::PhantomTool;
use anthropic::types::response::web_search::{WebSearchResponse, WebSearchToolCall};
use lazy_static::lazy_static;
diff --git a/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs b/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs
index 424dcc3088..e0eaf059b1 100644
--- a/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs
+++ b/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs
@@ -1,5 +1,5 @@
use crate::{RequestContext, ToolServiceContext};
-use ai::tool::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
diff --git a/rust/cloud-storage/ai_tools/src/web_fetch.rs b/rust/cloud-storage/ai_tools/src/web_fetch.rs
index 090bc407ac..ead07bd86e 100644
--- a/rust/cloud-storage/ai_tools/src/web_fetch.rs
+++ b/rust/cloud-storage/ai_tools/src/web_fetch.rs
@@ -1,4 +1,4 @@
-use ai::tool::schema::PhantomTool;
+use ai_toolset::schema::PhantomTool;
use anthropic::types::response::web_fetch::{WebFetchResponse, WebFetchToolCall};
use lazy_static::lazy_static;
diff --git a/rust/cloud-storage/ai_toolset/Cargo.toml b/rust/cloud-storage/ai_toolset/Cargo.toml
new file mode 100644
index 0000000000..ef9f160f33
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "ai_toolset"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+serde_json = { workspace = true }
+futures = { workspace = true }
+serde = { workspace = true }
+utoipa = { workspace = true }
+schemars = { workspace = true }
+async-trait = { workspace = true }
+thiserror = { workspace = true }
+anyhow = { workspace = true }
diff --git a/rust/cloud-storage/ai_toolset/src/lib.rs b/rust/cloud-storage/ai_toolset/src/lib.rs
new file mode 100644
index 0000000000..dd0f03424b
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/lib.rs
@@ -0,0 +1,51 @@
+//! AI Toolset library for building type-safe, schema-validated AI tool integrations.
+//!
+//! This crate provides infrastructure for defining tools that can be called by AI models,
+//! with automatic JSON schema generation for inputs and outputs. It supports both
+//! synchronous and asynchronous tools, and can generate tool definitions compatible
+//! with various AI APIs.
+//!
+//! # Features
+//!
+//! - Type-safe tool definitions using Rust traits
+//! - Automatic JSON schema generation via `schemars`
+//! - Support for both sync and async tools
+//! - Toolset management for grouping related tools
+//!
+//! # Example
+//!
+//! ```ignore
+//! use ai_toolset::{AsyncTool, ToolResult};
+//! use schemars::JsonSchema;
+//! use serde::{Deserialize, Serialize};
+//!
+//! #[derive(JsonSchema, Deserialize)]
+//! #[schemars(title = "Greet", description = "Greets a user by name")]
+//! struct GreetTool {
+//! name: String,
+//! }
+//!
+//! #[derive(Serialize, JsonSchema)]
+//! struct GreetOutput {
+//! message: String,
+//! }
+//!
+//! #[async_trait::async_trait]
+//! impl AsyncTool<(), ()> for GreetTool {
+//! type Output = GreetOutput;
+//! async fn call(&self, _: (), _: ()) -> ToolResult<Self::Output> {
+//! Ok(GreetOutput {
+//! message: format!("Hello, {}!", self.name),
+//! })
+//! }
+//! }
+//! ```
+
+#![deny(missing_docs)]
+
+pub mod schema;
+mod tool;
+mod toolset;
+
+pub use tool::*;
+pub use toolset::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/schema/generate.rs b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
similarity index 68%
rename from rust/cloud-storage/ai/src/tool/types/schema/generate.rs
rename to rust/cloud-storage/ai_toolset/src/schema/generate.rs
index 8b13413a7f..3231686892 100644
--- a/rust/cloud-storage/ai/src/tool/types/schema/generate.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
@@ -1,23 +1,35 @@
-use crate::tool::AsyncToolSet;
+use crate::AsyncToolSet;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+/// Schema information for a single tool, serializable for API responses.
#[derive(Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ToolSchema {
+ /// The name of the tool.
pub name: String,
+ /// The JSON schema for the tool's input parameters.
pub input_schema: serde_json::Value,
+ /// The JSON schema for the tool's output.
pub output_schema: serde_json::Value,
}
+/// A collection of tool schemas, typically used for API responses.
#[derive(Serialize, Deserialize, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ToolSchemas {
+ /// The list of tool schemas.
pub schemas: Vec<ToolSchema>,
}
+/// Trait for types that can generate tool schemas.
+///
+/// Implement this trait to provide schema information about available tools.
pub trait ToolSchemaGenerator {
+ /// Generates the schemas for all tools in this generator.
fn generate_schemas(&self) -> ToolSchemas;
+
+ /// Merges this generator's schemas with another generator's schemas.
fn merge(&self, generator: &dyn ToolSchemaGenerator) -> ToolSchemas {
let mut schemas = self.generate_schemas();
schemas
diff --git a/rust/cloud-storage/ai_toolset/src/schema/mod.rs b/rust/cloud-storage/ai_toolset/src/schema/mod.rs
new file mode 100644
index 0000000000..d759813ebf
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/schema/mod.rs
@@ -0,0 +1,10 @@
+//! Schema generation utilities for AI tools.
+//!
+//! This module provides types and traits for generating and managing
+//! tool schemas that describe tool inputs and outputs.
+
+mod generate;
+mod phantom_tool;
+
+pub use generate::*;
+pub use phantom_tool::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/schema/phantom_tool.rs b/rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rs
similarity index 58%
rename from rust/cloud-storage/ai/src/tool/types/schema/phantom_tool.rs
rename to rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rs
index f29a275f4e..c11d444c29 100644
--- a/rust/cloud-storage/ai/src/tool/types/schema/phantom_tool.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rs
@@ -3,16 +3,21 @@ use schemars::{JsonSchema, schema_for};
use std::fmt::Debug;
use std::marker::PhantomData;
-/// A tool that is not sent to AI but may be called by ai (built in tools)
-/// Generate schemas for these tools for the frontend
+/// A phantom tool for generating schemas without runtime tool instances.
+///
+/// This is useful for built-in tools that are not sent to the AI but may be
+/// called by the AI. The schemas can be generated for frontend display or
+/// documentation purposes.
#[derive(Clone, Debug)]
pub struct PhantomTool<I: Clone + Debug, O: Clone + Debug> {
i: PhantomData<I>,
o: PhantomData<O>,
+ /// The name of the phantom tool.
pub name: &'static str,
}
impl<I: Clone + Debug, O: Clone + Debug> PhantomTool<I, O> {
+ /// Creates a new phantom tool with the given name.
pub fn new(name: &'static str) -> Self {
PhantomTool {
i: PhantomData,
@@ -22,42 +27,6 @@ impl<I: Clone + Debug, O: Clone + Debug> PhantomTool<I, O> {
}
}
-impl PhantomTool<(), ()> {
- pub fn builder(name: &'static str) -> Self {
- PhantomTool {
- i: PhantomData,
- o: PhantomData,
- name,
- }
- }
-}
-
-impl<O: Clone + Debug> PhantomTool<(), O> {
- pub fn with_input_schema<I>(self) -> PhantomTool<I, O>
- where
- I: JsonSchema + Clone + Debug,
- {
- PhantomTool {
- i: PhantomData,
- o: PhantomData,
- name: self.name,
- }
- }
-}
-
-impl<I: Clone + Debug> PhantomTool<I, ()> {
- pub fn with_output_schema<O>(self) -> PhantomTool<I, O>
- where
- O: Clone + Debug + JsonSchema,
- {
- PhantomTool {
- i: PhantomData,
- o: PhantomData,
- name: self.name,
- }
- }
-}
-
impl<I, O> ToolSchemaGenerator for PhantomTool<I, O>
where
I: JsonSchema + Clone + Debug,
diff --git a/rust/cloud-storage/ai_toolset/src/tool.rs b/rust/cloud-storage/ai_toolset/src/tool.rs
new file mode 100644
index 0000000000..57dd858b1c
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/tool.rs
@@ -0,0 +1,58 @@
+use async_trait::async_trait;
+use serde::Serialize;
+
+/// Result type for tool calls, containing either the output or a [`ToolCallError`].
+pub type ToolResult<T> = std::result::Result<T, ToolCallError>;
+
+/// A unit type for tools that don't require any context.
+pub struct NoContext();
+
+/// Error type for failed tool calls.
+///
+/// Contains both an internal error for logging/debugging and a user-facing description.
+#[derive(Debug)]
+pub struct ToolCallError {
+ /// The underlying error that caused the tool call to fail.
+ pub internal_error: anyhow::Error,
+ /// A human-readable description of the error suitable for returning to the AI.
+ pub description: String,
+}
+
+impl std::fmt::Display for ToolCallError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "description: {}. error: {}",
+ self.description, self.internal_error
+ )
+ }
+}
+
+/// Trait for synchronous tools that can be called by an AI model.
+///
+/// # Type Parameters
+///
+/// - `Sc`: Service context type (shared state like database connections)
+/// - `Rc`: Request context type (per-request data like user info)
+pub trait Tool<Sc, Rc>: Sync + Send {
+ /// The output type produced by this tool.
+ type Output: Serialize + 'static;
+
+ /// Execute the tool with the given contexts.
+ fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output>;
+}
+
+/// Trait for asynchronous tools that can be called by an AI model.
+///
+/// # Type Parameters
+///
+/// - `Sc`: Service context type (shared state like database connections)
+/// - `Rc`: Request context type (per-request data like user info)
+#[async_trait]
+pub trait AsyncTool<Sc, Rc>: Sync + Send {
+ /// The output type produced by this tool.
+ type Output: Serialize + 'static;
+
+ /// Execute the tool asynchronously with the given contexts.
+ async fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output>;
+}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/mod.rs b/rust/cloud-storage/ai_toolset/src/toolset/mod.rs
new file mode 100644
index 0000000000..eb2a3281d4
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/toolset/mod.rs
@@ -0,0 +1,5 @@
+//! Toolset management for organizing and invoking AI tools.
+
+pub mod tool_object;
+mod types;
+pub use types::*;
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/json_tool.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs
similarity index 79%
rename from rust/cloud-storage/ai/src/tool/types/toolset/tool_object/json_tool.rs
rename to rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs
index 0452488b70..cb006448ee 100644
--- a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/json_tool.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs
@@ -1,9 +1,13 @@
-use crate::tool::types::ToolCallError;
-use crate::tool::{AsyncTool, Tool, ToolResult};
+use crate::ToolCallError;
+use crate::{AsyncTool, Tool, ToolResult};
+/// Wrapper that converts a synchronous tool's output to JSON.
+///
+/// This wraps a [`Tool`] and serializes its output to a [`serde_json::Value`].
pub struct JsonTool<Sc, Rc, O>(Box<dyn Tool<Sc, Rc, Output = O>>);
impl<Sc, Rc, O> JsonTool<Sc, Rc, O> {
+ /// Creates a new `JsonTool` from a boxed tool.
pub fn from_boxed<T>(t: Box<T>) -> Self
where
T: Tool<Sc, Rc, Output = O> + 'static,
@@ -13,9 +17,13 @@ impl<Sc, Rc, O> JsonTool<Sc, Rc, O> {
}
}
+/// Wrapper that converts an asynchronous tool's output to JSON.
+///
+/// This wraps an [`AsyncTool`] and serializes its output to a [`serde_json::Value`].
pub struct JsonAsyncTool<Sc, Rc, O>(Box<dyn AsyncTool<Sc, Rc, Output = O>>);
impl<Sc, Rc, O> JsonAsyncTool<Sc, Rc, O> {
+ /// Creates a new `JsonAsyncTool` from a boxed async tool.
pub fn from_boxed<T>(t: Box<T>) -> Self
where
T: AsyncTool<Sc, Rc, Output = O> + 'static,
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs
new file mode 100644
index 0000000000..7dc9e91df0
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs
@@ -0,0 +1,18 @@
+//! Tool object types for runtime tool invocation.
+//!
+//! This module contains the compiled tool representations that enable
+//! runtime deserialization and invocation of tools.
+
+#[macro_use]
+mod util;
+
+mod json_tool;
+mod object;
+mod tool;
+mod tool_async;
+
+pub use json_tool::*;
+pub use object::*;
+pub use tool::*;
+pub use tool_async::*;
+pub use util::*;
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs
new file mode 100644
index 0000000000..01b0f4749f
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs
@@ -0,0 +1,40 @@
+use serde_json::Error as JsonError;
+use serde_json::Value;
+use thiserror::Error;
+
+/// A compiled tool object containing schema and deserialization logic.
+///
+/// `ToolObject` holds the metadata and deserializer for a tool, allowing
+/// it to be invoked with JSON input at runtime.
+pub struct ToolObject<T> {
+ /// The JSON schema describing the tool's input parameters.
+ pub input_schema: Value,
+ /// The JSON schema describing the tool's output.
+ pub output_schema: Value,
+ /// A human-readable description of what the tool does.
+ pub description: String,
+ /// The unique name of the tool.
+ pub name: String,
+ /// The deserializer function for converting JSON to the tool type.
+ pub deserializer: T,
+}
+
+/// Errors that can occur when validating a tool's schema.
+#[derive(Debug, Error)]
+pub enum ValidationError {
+ /// The schema is missing required metadata (title or description).
+ #[error("missing metadata")]
+ MissingMetadata,
+ /// Failed to serialize the schema to JSON.
+ #[error("could not convert to json")]
+ JsonSerialization(JsonError),
+ /// The schema contains nested objects which are not supported.
+ #[error("schema exceeds depth one - nested objects with properties are not allowed")]
+ ExceedsDepthOne,
+ /// The schema title is empty.
+ #[error("title is empty")]
+ EmptyTitle,
+ /// The schema contains `oneOf` which is not supported for AI tools.
+ #[error("schema must not have oneOf set. Do not use descriptions or /// on enum types.")]
+ OneOf,
+}
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/tool.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool.rs
similarity index 77%
rename from rust/cloud-storage/ai/src/tool/types/toolset/tool_object/tool.rs
rename to rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool.rs
index a916d76e26..4adc583dca 100644
--- a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/tool.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool.rs
@@ -1,5 +1,4 @@
-use crate::tool::types::Tool;
-use async_openai::types::{ChatCompletionTool, ChatCompletionToolType, FunctionObject};
+use crate::Tool;
use schemars::JsonSchema;
use serde::Serialize;
use serde::de::Deserialize;
@@ -14,10 +13,12 @@ type Deserializer<Sc, Rc> = Box<
dyn Fn(&serde_json::Value) -> Result<ToolTraitObject<Sc, Rc>, serde_json::Error> + Send + Sync,
>;
+/// Type alias for a [`ToolObject`] configured for synchronous tools.
pub type SyncToolObject<Context, RequestContext> =
ToolObject<Deserializer<Context, RequestContext>>;
impl<Sc, Rc> ToolObject<Deserializer<Sc, Rc>> {
+ /// Attempts to deserialize JSON input into a callable tool instance.
pub fn try_deserialize(
&self,
data: &serde_json::Value,
@@ -26,6 +27,10 @@ impl<Sc, Rc> ToolObject<Deserializer<Sc, Rc>> {
deserializer(data)
}
+ /// Creates a new [`SyncToolObject`] from a tool type.
+ ///
+ /// The tool type must implement [`Tool`], [`JsonSchema`], and [`Deserialize`].
+ /// Returns an error if schema validation fails.
pub fn try_from_tool<T>() -> Result<Self, ValidationError>
where
T: JsonSchema + Tool<Sc, Rc> + Send + Sync + for<'de> Deserialize<'de> + 'static,
@@ -60,17 +65,3 @@ impl<Sc, Rc> ToolObject<Deserializer<Sc, Rc>> {
})
}
}
-
-impl<T> From<&ToolObject<T>> for ChatCompletionTool {
- fn from(value: &ToolObject<T>) -> Self {
- Self {
- r#type: ChatCompletionToolType::Function,
- function: FunctionObject {
- name: value.name.clone(),
- description: Some(value.description.clone()),
- parameters: Some(value.input_schema.clone()),
- strict: Some(true),
- },
- }
- }
-}
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/tool_async.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
similarity index 87%
rename from rust/cloud-storage/ai/src/tool/types/toolset/tool_object/tool_async.rs
rename to rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
index 4f3343d730..90ac30f594 100644
--- a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/tool_async.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
@@ -1,4 +1,4 @@
-use crate::tool::types::{AsyncTool, Tool, ToolResult};
+use crate::{AsyncTool, Tool, ToolResult};
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::Serialize;
@@ -17,10 +17,12 @@ type AsyncDeserializer<Sc, Rc> = Box<
+ Sync,
>;
+/// Type alias for a [`ToolObject`] configured for asynchronous tools.
pub type AsyncToolObject<Context, RequestContext> =
ToolObject<AsyncDeserializer<Context, RequestContext>>;
impl<Sc, Rc> ToolObject<AsyncDeserializer<Sc, Rc>> {
+ /// Attempts to deserialize JSON input into a callable async tool instance.
pub fn try_deserialize(
&self,
data: &serde_json::Value,
@@ -31,6 +33,10 @@ impl<Sc, Rc> ToolObject<AsyncDeserializer<Sc, Rc>> {
}
impl<Sc, Rc> ToolObject<AsyncDeserializer<Sc, Rc>> {
+ /// Creates a new [`AsyncToolObject`] from an async tool type.
+ ///
+ /// The tool type must implement [`AsyncTool`], [`JsonSchema`], and [`Deserialize`].
+ /// Returns an error if schema validation fails.
pub fn try_from_tool<T, O>() -> Result<Self, ValidationError>
where
T: JsonSchema
@@ -92,6 +98,7 @@ where
}
}
+/// Wrapper that adapts a synchronous [`Tool`] to implement [`AsyncTool`].
pub struct AsyncToolWrapper<Sc, Rc, O>(pub Box<dyn Tool<Sc, Rc, Output = O> + Send + Sync>);
#[async_trait]
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/util.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/util.rs
similarity index 86%
rename from rust/cloud-storage/ai/src/tool/types/toolset/tool_object/util.rs
rename to rust/cloud-storage/ai_toolset/src/toolset/tool_object/util.rs
index a68e8e1fe3..68f7e1e1a8 100644
--- a/rust/cloud-storage/ai/src/tool/types/toolset/tool_object/util.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/util.rs
@@ -5,8 +5,10 @@ use schemars::{
transform::{RecursiveTransform, Transform},
};
-// validates the input schema for a tool using custom validation for OpenAI spec
-// see: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas
+/// Validates a tool's input schema against OpenAI's structured output requirements.
+///
+/// Returns the tool's name and description extracted from the schema metadata.
+/// See: <https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas>
pub fn validate_tool_schema(schema: &Schema) -> Result<(String, String), ValidationError> {
let name = schema
.get("title")
@@ -143,6 +145,10 @@ impl Transform for AdditionalPropertiesFalse {
}
}
+/// Creates a schema generator configured for tool input schemas.
+///
+/// The generated schemas include `required` arrays for all properties and
+/// `additionalProperties: false` as required by OpenAI's structured outputs.
pub fn input_schema_generator() -> SchemaGenerator {
SchemaSettings::draft2020_12()
.with(|s| {
@@ -154,11 +160,13 @@ pub fn input_schema_generator() -> SchemaGenerator {
.into_generator()
}
+/// Schema transform that simplifies output schemas for AI consumption.
+///
+/// Removes unnecessary fields like `title`, `format`, `required`, `type`, etc.,
+/// keeping only property names and descriptions.
#[derive(Debug, Clone)]
pub struct MinimizedOutput;
-// Simplifies schema to only include property names and descriptions for AI consumption
-// Not an exact match, but should be good enough for now
impl Transform for MinimizedOutput {
fn transform(&mut self, schema: &mut Schema) {
if let Some(obj) = schema.as_object_mut() {
@@ -173,6 +181,9 @@ impl Transform for MinimizedOutput {
}
}
+/// Creates a schema generator that produces minimized output schemas.
+///
+/// Uses [`MinimizedOutput`] transform to strip unnecessary schema fields.
pub fn minimized_output_schema_generator() -> SchemaGenerator {
SchemaSettings::draft2020_12()
.with(|s| {
@@ -183,6 +194,9 @@ pub fn minimized_output_schema_generator() -> SchemaGenerator {
.into_generator()
}
+/// Creates a schema generator for tool output schemas.
+///
+/// Uses draft 2020-12 settings with inlined subschemas and no meta schema.
pub fn output_schema_generator() -> SchemaGenerator {
SchemaSettings::draft2020_12()
.with(|s| {
@@ -192,18 +206,25 @@ pub fn output_schema_generator() -> SchemaGenerator {
.into_generator()
}
+/// Generates a JSON schema for a tool's input parameters.
+///
+/// Uses [`input_schema_generator`] to create a schema compliant with
+/// OpenAI's structured output requirements.
#[macro_export]
macro_rules! generate_tool_input_schema {
($tool:ty) => {{
- use $crate::tool::types::tool_object::input_schema_generator;
+ use $crate::tool_object::input_schema_generator;
input_schema_generator().into_root_schema_for::<$tool>()
}};
}
+/// Generates a JSON schema for a tool's output type.
+///
+/// Uses [`output_schema_generator`] to create a standard JSON schema.
#[macro_export]
macro_rules! generate_tool_output_schema {
($tool:ty) => {{
- use $crate::tool::types::tool_object::output_schema_generator;
+ use $crate::tool_object::output_schema_generator;
output_schema_generator().into_root_schema_for::<$tool>()
}};
}
diff --git a/rust/cloud-storage/ai/src/tool/types/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
similarity index 70%
rename from rust/cloud-storage/ai/src/tool/types/toolset/types.rs
rename to rust/cloud-storage/ai_toolset/src/toolset/types.rs
index 6a4ee08536..7fcaca82ba 100644
--- a/rust/cloud-storage/ai/src/tool/types/toolset/types.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
@@ -1,39 +1,51 @@
use super::tool_object::{AsyncToolObject, SyncToolObject, ValidationError};
-use crate::tool::{AsyncTool, Tool, ToolResult};
-use async_openai::types::ChatCompletionTool;
+use crate::{AsyncTool, Tool, ToolResult};
use schemars::{JsonSchema, Schema};
use serde::Serialize;
use serde::de::Deserialize;
use std::collections::hash_map::HashMap;
use thiserror::Error;
+/// Error type for failures when creating or adding tools to a toolset.
#[derive(Debug, Error)]
pub enum ToolSetCreationError {
+ /// Schema validation failed for the tool.
#[error("error validating schema")]
Validation(ValidationError),
+ /// A tool with the same name already exists in the toolset.
#[error("two or more tools have the same name")]
NameConflict(String),
}
+/// Error type for failures when invoking tools from a toolset.
#[derive(Debug, Error)]
pub enum ToolSetError {
+ /// Failed to deserialize the tool input (possibly an AI hallucination).
#[error("error deserializing tool call (possible hallucination)")]
Deserialization(serde_json::Error),
+ /// The requested tool was not found in the toolset.
#[error("tool not in toolset")]
NotFound(String),
}
+/// Type alias for a toolset containing synchronous tools.
pub type SyncToolSet<Context, RequestContext> = ToolSet<SyncToolObject<Context, RequestContext>>;
+/// Type alias for a toolset containing asynchronous tools.
pub type AsyncToolSet<Context, RequestContext> = ToolSet<AsyncToolObject<Context, RequestContext>>;
+/// Represents the schema information for a tool.
pub struct ToolSchema {
+ /// The name of the tool.
pub name: String,
+ /// The JSON schema for the tool's input parameters.
pub schema: Schema,
+ /// The JSON schema for the tool's output.
pub result_schema: Schema,
}
impl ToolSchema {
+ /// Creates a new tool schema with the given name, input schema, and result schema.
pub fn new(name: String, schema: Schema, result_schema: Schema) -> Self {
Self {
name,
@@ -43,12 +55,18 @@ impl ToolSchema {
}
}
+/// A collection of tools that can be called by an AI model.
+///
+/// `ToolSet` manages a set of tools, allowing you to add tools, merge toolsets,
+/// and invoke tools by name with JSON input.
#[derive(Default)]
pub struct ToolSet<T> {
+ /// The tools in this toolset, keyed by name.
pub tools: HashMap<String, T>,
}
impl<T> ToolSet<T> {
+ /// Creates a new empty toolset.
pub fn new() -> Self {
Self {
tools: HashMap::new(),
@@ -61,6 +79,10 @@ where
Rc: Sync + Send + 'static,
Sc: Sync + Send + 'static,
{
+ /// Adds a synchronous tool to this toolset.
+ ///
+ /// The tool type must implement [`Tool`], [`JsonSchema`], and [`Deserialize`].
+ /// Returns an error if schema validation fails or a tool with the same name exists.
pub fn add_tool<T>(mut self) -> Result<Self, ToolSetCreationError>
where
T: JsonSchema + Tool<Sc, Rc> + for<'de> Deserialize<'de> + 'static + Send + Sync,
@@ -76,6 +98,9 @@ where
}
}
+ /// Attempts to call a tool by name with the given JSON input.
+ ///
+ /// Returns an error if the tool is not found or if deserialization fails.
pub fn try_tool_call(
&self,
context: Sc,
@@ -96,6 +121,9 @@ where
}
impl<T> ToolSet<T> {
+ /// Merges another toolset into this one.
+ ///
+ /// Returns an error if any tool names conflict between the two toolsets.
pub fn add_toolset(mut self, toolset: ToolSet<T>) -> Result<Self, ToolSetCreationError> {
for (name, _) in toolset.tools.iter() {
if self.tools.contains_key(name) {
@@ -112,6 +140,9 @@ where
Sc: Send + Sync + 'static,
Rc: Send + Sync + 'static,
{
+ /// Converts this synchronous toolset into an asynchronous toolset.
+ ///
+ /// Each synchronous tool is wrapped to be callable in an async context.
pub fn into_async(self) -> AsyncToolSet<Sc, Rc> {
AsyncToolSet {
tools: self
@@ -128,6 +159,10 @@ where
Rc: Sync + Send + 'static,
Sc: Sync + Send + 'static,
{
+ /// Adds an asynchronous tool to this toolset.
+ ///
+ /// The tool type must implement [`AsyncTool`], [`JsonSchema`], and [`Deserialize`].
+ /// Returns an error if schema validation fails or a tool with the same name exists.
pub fn add_tool<T>(mut self) -> Result<Self, ToolSetCreationError>
where
T: JsonSchema + AsyncTool<Sc, Rc> + for<'de> Deserialize<'de> + 'static + Send + Sync,
@@ -143,6 +178,9 @@ where
}
}
+ /// Attempts to call a tool by name with the given JSON input.
+ ///
+ /// Returns an error if the tool is not found or if deserialization fails.
pub async fn try_tool_call(
&self,
context: Sc,
@@ -162,15 +200,6 @@ where
}
}
-impl<T> ToolSet<T>
-where
- ChatCompletionTool: for<'a> From<&'a T>,
-{
- pub fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTool> {
- self.tools.values().map(ChatCompletionTool::from).collect()
- }
-}
-
impl<T> std::fmt::Debug for ToolSet<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut list = f.debug_list();