Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: ai tool for creating documents (#1649)
Will Hutchinson1ec28873ffb2
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 65f03e9e40..e568c8af52 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2974,6 +2974,7 @@ dependencies = ["schemars","serde","serde_json",+ "sha2","sqlx","sync_service_client","thiserror 2.0.17",diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.tomlindex 063a8bdd36..dc5c68b149 100644--- a/rust/cloud-storage/documents/Cargo.toml+++ b/rust/cloud-storage/documents/Cargo.toml@@ -16,6 +16,7 @@ ai_tools = ["dep:lexical_client","dep:model_file_type","dep:reqwest",+ "dep:sha2","ports","outbound"]@@ -45,7 +46,7 @@ macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }models_permissions = { path = "../models_permissions" }-macro_aws_config = { path = "../macro_aws_config" }+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }# Async runtime (for ports)tokio = { workspace = true, optional = true }@@ -75,6 +76,7 @@ schemars = { workspace = true, optional = true }lexical_client = { path = "../lexical_client", optional = true }model_file_type = { path = "../model_file_type", optional = true }reqwest = { workspace = true, optional = true }+sha2 = { workspace = true, optional = true }[dev-dependencies]http-body-util = { workspace = true }diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rsindex c58e5d2cbe..2b24165f5c 100644--- a/rust/cloud-storage/documents/examples/documents_toolset.rs+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs@@ -13,6 +13,8 @@//! DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL=...//! DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME=THE PRIVATE KEY//! DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID=...+//! DOCUMENT_STORAGE_BUCKET=...+//! DOCX_DOCUMENT_UPLOAD_BUCKET=...//! cargo run --example documents_toolset//! ```@@ -20,43 +22,19 @@ use ai::tool::tool_loop::cli::Cli;use ai::tool::types::RequestContext;use ai::types::Model;use documents::domain::models::CloudFrontConfig;-use documents::domain::ports::{PresignedUploadUrlPort, TaskPropertiesPort};+use documents::domain::ports::TaskPropertiesPort;use documents::domain::service::DocumentServiceImpl;use documents::inbound::toolset::{DocumentToolContext, document_toolset};use documents::outbound::pg_document_repo::PgDocumentRepo;+use documents::outbound::s3_upload_url::S3UploadUrlAdapter;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;use lexical_client::LexicalClient;use macro_user_id::user_id::MacroUserIdStr;-use model::document::ContentType;use sqlx::PgPool;use std::sync::Arc;use sync_service_client::SyncServiceClient;-/// No-op presigned upload URL service (not needed for toolset example).-#[derive(Clone)]-struct NoOpUploadUrl;--impl PresignedUploadUrlPort for NoOpUploadUrl {- async fn put_document_storage_presigned_url(- &self,- _key: &str,- _sha: &str,- _content_type: ContentType,- ) -> anyhow::Result<String> {- anyhow::bail!("not implemented in example")- }-- async fn put_docx_upload_presigned_url(- &self,- _key: &str,- _sha: &str,- _content_type: ContentType,- ) -> anyhow::Result<String> {- anyhow::bail!("not implemented in example")- }-}-/// No-op task properties service (not needed for toolset example).#[derive(Clone)]struct NoOpTaskProperties;@@ -68,11 +46,12 @@ impl TaskPropertiesPort for NoOpTaskProperties {}/// The prompt to use in the example.-const PROMPT: &str = "You are an assistant that helps users explore and manage their documents. Use the available tools to read document metadata.";+const PROMPT: &str = "You are an assistant that helps users explore, create and manage their documents. Use the available tools to create and read documents.";#[tokio::main]async fn main() {dotenvy::dotenv().ok();+// Get database URL from environmentlet database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");let usr = std::env::var("LOCAL_USER_ID").expect("LOCAL_USER_ID must bes set");@@ -97,6 +76,15 @@ async fn main() {let entity_access_repo = PgAccessRepository::new(pool.clone());let entity_access_service = EntityAccessServiceImpl::new(entity_access_repo);+ let document_storage_bucket =+ std::env::var("DOCUMENT_STORAGE_BUCKET").expect("DOCUMENT_STORAGE_BUCKET must be set");+ let docx_upload_bucket = std::env::var("DOCX_DOCUMENT_UPLOAD_BUCKET")+ .expect("DOCX_DOCUMENT_UPLOAD_BUCKET must be set");++ let s3_client = macro_aws_config::s3_client().await;+ let s3_upload_adapter =+ S3UploadUrlAdapter::new(s3_client, document_storage_bucket, docx_upload_bucket);+let documents_repo = PgDocumentRepo::new(pool.clone());let documents_service = DocumentServiceImpl::new(documents_repo,@@ -117,7 +105,7 @@ async fn main() {browser_cache_expiry_seconds: 900,},SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url),- NoOpUploadUrl,+ s3_upload_adapter,NoOpTaskProperties,pool,);diff --git a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rsnew file mode 100644index 0000000000..34370a4fa3--- /dev/null+++ b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs@@ -0,0 +1,160 @@+//! CreateDocument tool for reading document content.++use base64::Engine;+use sha2::Digest;+use sha2::Sha256;+use std::str::FromStr;++use crate::domain::{models::CreateDocumentRepoArgs, ports::DocumentService};+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use anyhow::Context;+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use macro_user_id::user_id::MacroUserIdStr;+use model_file_type::FileType;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++use super::DocumentToolContext;++/// The read content response+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateDocumentResponse {+ /// The id of the document+ pub document_id: uuid::Uuid,+}++#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]+#[serde(rename_all = "camelCase")]+#[schemars(title = "CreateDocument", description = "Create a document")]+pub struct CreateDocument {+ #[schemars(description = "The name of the document without the file extension")]+ pub document_name: String,++ #[schemars(description = "The raw bytes of the local file you created.")]+ pub file_content_bytes: Vec<u8>,++ #[schemars(description = "The extension of the file you are going to create.")]+ pub file_extension: String,+}++#[async_trait]+impl<DSvc, ESvc> AsyncTool<DocumentToolContext<DSvc, ESvc>> for CreateDocument+where+ DSvc: DocumentService,+ ESvc: EntityAccessService,+{+ type Output = CreateDocumentResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!(params=?self, "Create content");++ let parsed_file_type =+ FileType::from_str(&self.file_extension).map_err(|e| ToolCallError {+ description: format!("invalid file extension {}", self.file_extension),+ internal_error: e.into(),+ })?;+ let content_type = parsed_file_type.mime_type();+ let file_type: Option<FileType> = Some(parsed_file_type);++ let user_id: MacroUserIdStr<'static> = (*request_context.user_id).clone();++ let hashes = get_file_shas(&self.file_content_bytes).map_err(|e| ToolCallError {+ description: "could not get file content shas".to_string(),+ internal_error: e,+ })?;+ tracing::trace!("got file shas");++ let document_response = service_context+ .service+ .create_document(+ user_id.clone(),+ CreateDocumentRepoArgs {+ id: None,+ sha: hashes.0,+ document_name: self.document_name.clone(),+ user_id,+ file_type,+ project_id: None,+ email_attachment_id: None,+ created_at: None,+ is_task: false,+ skip_history: false,+ },+ None, // job_id+ )+ .await+ .map_err(|e| ToolCallError {+ description: "failed to create document".to_string(),+ internal_error: e.into(),+ })?;+ tracing::trace!("created document");++ let document_response = document_response.document_response;+ let document_metadata = document_response.document_metadata;++ let presigned_url = document_response+ .presigned_url+ .context("expected presigned url")+ .map_err(|e| ToolCallError {+ description: "presigned url was not generated".to_string(),+ internal_error: e,+ })?;++ let upload_response = reqwest::Client::new()+ .put(&presigned_url)+ .header("content-type", content_type)+ .header("x-amz-checksum-sha256", &hashes.1)+ .body(self.file_content_bytes.clone())+ .send()+ .await+ .map_err(|e| ToolCallError {+ description: "failed to upload file to presigned url".to_string(),+ internal_error: e.into(),+ })?;++ if !upload_response.status().is_success() {+ let status = upload_response.status();+ let body = upload_response.text().await.unwrap_or_default();+ return Err(ToolCallError {+ description: format!("presigned url upload failed with status {status}"),+ internal_error: anyhow::anyhow!("upload failed: {status} {body}"),+ });+ }++ tracing::info!("uploaded file");++ let document_id = document_metadata+ .document_id+ .parse()+ .context("expected valid uuid")+ .map_err(|e| ToolCallError {+ internal_error: e,+ description: format!(+ "invalid document id was output {}",+ document_metadata.document_id+ ),+ })?;++ tracing::info!("got to end");+ Ok(CreateDocumentResponse { document_id })+ }+}++#[tracing::instrument(skip(file_content), err)]+pub fn get_file_shas(file_content: &[u8]) -> anyhow::Result<(String, String)> {+ let mut hasher = Sha256::new();+ hasher.update(file_content);+ let file_hash_result = hasher.finalize();+ let base64_encoded_sha = base64::engine::general_purpose::STANDARD.encode(file_hash_result);++ let hash = format!("{:x}", file_hash_result);++ Ok((hash, base64_encoded_sha))+}diff --git a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs b/rust/cloud-storage/documents/src/inbound/toolset/mod.rsindex f72aa70274..0233f75a78 100644--- a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs+++ b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs@@ -1,5 +1,6 @@//! Toolset inbound adapter for Documents.+mod create_document;mod read_content;mod read_metadata;@@ -8,7 +9,9 @@ mod test;use crate::{domain::ports::DocumentService,- inbound::toolset::{read_content::ReadContent, read_metadata::ReadMetadata},+ inbound::toolset::{+ create_document::CreateDocument, read_content::ReadContent, read_metadata::ReadMetadata,+ },};use ai::tool::AsyncToolSet;use entity_access::domain::ports::EntityAccessService;@@ -58,4 +61,6 @@ where.expect("failed to add ReadMetadata tool").add_tool::<ReadContent, DocumentToolContext<DSvc, ESvc>>().expect("failed to add ReadContent tool")+ .add_tool::<CreateDocument, DocumentToolContext<DSvc, ESvc>>()+ .expect("failed to add CreateDocument tool")}diff --git a/rust/cloud-storage/documents/src/inbound/toolset/test.rs b/rust/cloud-storage/documents/src/inbound/toolset/test.rsindex 7c69d5eee8..cd22bc212a 100644--- a/rust/cloud-storage/documents/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/documents/src/inbound/toolset/test.rs@@ -37,3 +37,21 @@ fn test_read_content_schema_validation() {"Description should contain expected text");}++#[test]+fn test_create_document_schema_validation() {+ let schema = generate_tool_input_schema!(CreateDocument);++ let result = validate_tool_schema(&schema);+ assert!(result.is_ok(), "{:?}", result);++ let (name, description) = result.unwrap();+ assert_eq!(+ name, "CreateDocument",+ "Tool name should match the schemars title"+ );+ assert!(+ description.contains("Create"),+ "Description should contain expected text"+ );+}