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): small attachment refactor (#841)

Eric Hayes12e939c0afea
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 8fba0ffe18..046e99cfdd 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -45,16 +45,18 @@ dependencies = [
name = "ai"
version = "0.1.0"
dependencies = [
- "ai_format",
"anthropic",
"anyhow",
"async-openai",
"async-stream",
"async-trait",
+ "base64 0.22.1",
"chrono",
"const_format",
"futures",
+ "image",
"lazy_static",
+ "model_file_type",
"rand 0.9.0",
"reqwest",
"schemars",
@@ -67,12 +69,14 @@ dependencies = [
"tokio",
"tracing",
"utoipa",
+ "webp",
]
[[package]]
name = "ai_format"
version = "0.1.0"
dependencies = [
+ "ai",
"chrono",
]
@@ -81,6 +85,7 @@ name = "ai_tools"
version = "0.1.0"
dependencies = [
"ai",
+ "ai_format",
"anthropic",
"anyhow",
"async-trait",
@@ -2653,6 +2658,7 @@ version = "0.1.0"
dependencies = [
"aho-corasick",
"ai",
+ "ai_format",
"ai_tools",
"anyhow",
"async-openai",
@@ -7676,7 +7682,6 @@ dependencies = [
"doppleganger",
"email_service_client",
"futures",
- "image",
"lexical_client",
"macro_client_errors",
"model",
@@ -7694,7 +7699,6 @@ dependencies = [
"tokio",
"tracing",
"uuid",
- "webp",
]
[[package]]
diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.toml
index 78c5afcf44..a66d9128e8 100644
--- a/rust/cloud-storage/ai/Cargo.toml
+++ b/rust/cloud-storage/ai/Cargo.toml
@@ -8,7 +8,6 @@ version = "0.1.0"
tokio = { workspace = true }
[dependencies]
-ai_format = { path = "../ai_format" }
anyhow = { workspace = true }
async-openai = { workspace = true }
async-stream = { workspace = true }
@@ -30,3 +29,7 @@ tokio.workspace = true
tracing = { workspace = true }
utoipa = { workspace = true }
anthropic = { path = "../anthropic" }
+base64 = { workspace = true }
+image = "0.25.9"
+webp = "0.3.1"
+model_file_type = { path = "../model_file_type"}
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs
index 174b8f58e3..3aff2a7a34 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs
@@ -128,7 +128,7 @@ where
// tell the primary model how all the tools will work
request
.system_prompt
- .content
+ .instructions
.push_str(&build_tool_prompt(&self.toolset));
self.request = request.try_into()?;
@@ -174,9 +174,9 @@ where
.build(),
],
system_prompt: SystemPrompt {
- attachments: vec![],
- content: "Use the tool provided in context following the user instructions"
- .into(),
+ attachments: Default::default(),
+ instructions:
+ "Use the tool provided in context following the user instructions".into(),
},
},
selected_tool,
diff --git a/rust/cloud-storage/ai/src/traits.rs b/rust/cloud-storage/ai/src/traits.rs
index 03e11024b0..38d25f9637 100644
--- a/rust/cloud-storage/ai/src/traits.rs
+++ b/rust/cloud-storage/ai/src/traits.rs
@@ -4,3 +4,7 @@ pub trait Metadata: for<'de> Deserialize<'de> {
fn name() -> String;
fn description() -> Option<String>;
}
+
+pub trait TextAttachment: std::fmt::Display + std::fmt::Debug + Send + Sync {}
+
+impl TextAttachment for Box<dyn TextAttachment> {}
diff --git a/rust/cloud-storage/ai/src/types/message/base_64_image.rs b/rust/cloud-storage/ai/src/types/message/base_64_image.rs
new file mode 100644
index 0000000000..fb34e96e00
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/message/base_64_image.rs
@@ -0,0 +1,144 @@
+use anyhow::{anyhow, bail};
+use base64::Engine;
+use base64::engine::general_purpose;
+use image::{DynamicImage, GenericImageView};
+use model_file_type::FileType;
+use webp::Encoder;
+
+const ENCODING_QUALITY: f32 = 75.0;
+const MAX_SIZE_W: u32 = 1080;
+const MAX_SIZE_H: u32 = 720;
+
+#[derive(Eq, PartialEq, Clone)]
+pub struct Base64Image {
+ data: String,
+ format: ImageFormat,
+}
+
+#[derive(Clone, Debug, Copy, Eq, PartialEq)]
+pub enum ImageFormat {
+ WebP,
+ Jpg,
+ Jpeg,
+ Png,
+}
+
+impl TryFrom<FileType> for ImageFormat {
+ type Error = anyhow::Error;
+ fn try_from(value: FileType) -> Result<Self, Self::Error> {
+ match value {
+ FileType::Jpg => Ok(Self::Jpg),
+ FileType::Jpeg => Ok(Self::Jpeg),
+ FileType::Png => Ok(Self::Png),
+ FileType::Webp => Ok(Self::WebP),
+ _ => bail!("No conversion"),
+ }
+ }
+}
+
+impl Base64Image {
+ pub fn compress_and_reencode(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
+ Self::make_compressed_base64_webp(bytes)
+ }
+
+ pub(crate) fn dangerously_try_from_string(s: String) -> Result<Self, anyhow::Error> {
+ let prefix = s.split_once(";").ok_or(anyhow!("Unexpected format"))?.0;
+ let image = prefix
+ .split_once("/")
+ .ok_or(anyhow!("Unexpected format"))?
+ .1;
+ let format = ImageFormat::try_from(image)?;
+ Ok(Self { data: s, format })
+ }
+}
+
+impl Base64Image {
+ fn prefix(&self) -> String {
+ format!("data:image/{};base64,", self.format)
+ }
+}
+
+impl std::fmt::Display for Base64Image {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}{}", self.prefix(), self.data)
+ }
+}
+
+impl std::fmt::Display for ImageFormat {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "{}",
+ match self {
+ Self::WebP => "webp",
+ Self::Jpg => "jpg",
+ Self::Jpeg => "jpeg",
+ Self::Png => "png",
+ }
+ )
+ }
+}
+
+impl std::fmt::Debug for Base64Image {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}[{} bytes]", self.prefix(), self.data.len())
+ }
+}
+
+impl Base64Image {
+ fn make_compressed_base64_webp(image_bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
+ let img = image::load_from_memory(&image_bytes)?;
+ let resized_img = Self::resize_if_needed(img);
+ let rgb_img = resized_img.to_rgb8();
+ let encoder = Encoder::from_rgb(&rgb_img, rgb_img.width(), rgb_img.height());
+ let webp_data = encoder.encode(ENCODING_QUALITY);
+ let base64_string = general_purpose::STANDARD.encode(&*webp_data);
+ Ok(Self {
+ data: base64_string,
+ format: ImageFormat::WebP,
+ })
+ }
+
+ fn resize_if_needed(img: DynamicImage) -> DynamicImage {
+ let (width, height) = img.dimensions();
+
+ // Check if resize is needed
+ if width <= MAX_SIZE_W && height <= MAX_SIZE_H {
+ return img;
+ }
+
+ // Calculate new dimensions while maintaining aspect ratio
+ let width_ratio = MAX_SIZE_W as f32 / width as f32;
+ let height_ratio = MAX_SIZE_H as f32 / height as f32;
+ let ratio = width_ratio.min(height_ratio);
+
+ let new_width = (width as f32 * ratio) as u32;
+ let new_height = (height as f32 * ratio) as u32;
+
+ img.resize(new_width, new_height, image::imageops::FilterType::Lanczos3)
+ }
+}
+
+impl From<ImageFormat> for image::ImageFormat {
+ fn from(value: ImageFormat) -> Self {
+ match value {
+ ImageFormat::Jpeg => Self::Jpeg,
+ ImageFormat::Jpg => Self::Jpeg,
+ ImageFormat::WebP => Self::WebP,
+ ImageFormat::Png => Self::Png,
+ }
+ }
+}
+
+impl TryFrom<&str> for ImageFormat {
+ type Error = anyhow::Error;
+ fn try_from(value: &str) -> Result<Self, Self::Error> {
+ match value {
+ "webp" => Ok(Self::WebP),
+ "jpg" => Ok(Self::Jpg),
+ "jpeg" => Ok(Self::Jpeg),
+ "png" => Ok(Self::Png),
+ _ => bail!("No conversion"),
+ }
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/message/chat_message.rs b/rust/cloud-storage/ai/src/types/message/chat_message.rs
index 58de1f001f..5793d2d888 100644
--- a/rust/cloud-storage/ai/src/types/message/chat_message.rs
+++ b/rust/cloud-storage/ai/src/types/message/chat_message.rs
@@ -1,19 +1,20 @@
use super::Role;
use crate::tokens::{TokenCount, count_tokens};
+use crate::types::request::ImageData;
use anyhow::Result;
use async_openai::types::ChatCompletionRequestMessage;
use serde::{self, Deserialize, Serialize};
use std::fmt::{Display, Write};
use utoipa::ToSchema;
-#[derive(Clone, Debug, Eq, PartialEq)]
+#[derive(Debug, Eq, PartialEq, Clone)]
pub struct ChatMessages(pub Vec<ChatMessage>);
-#[derive(Clone, Debug, Eq, PartialEq)]
+#[derive(Debug, Eq, PartialEq, Clone)]
pub struct ChatMessage {
pub content: ChatMessageContent,
pub role: Role,
- pub image_urls: Option<Vec<String>>,
+ pub image_urls: Option<Vec<ImageData>>,
}
impl TokenCount for ChatMessage {
diff --git a/rust/cloud-storage/ai/src/types/message/message_builder.rs b/rust/cloud-storage/ai/src/types/message/message_builder.rs
index 207dd1af82..657eb087a4 100644
--- a/rust/cloud-storage/ai/src/types/message/message_builder.rs
+++ b/rust/cloud-storage/ai/src/types/message/message_builder.rs
@@ -1,9 +1,9 @@
-use crate::types::{ChatMessage, ChatMessageContent, Role};
+use crate::types::{ChatMessage, ChatMessageContent, ImageData, Role};
pub struct MessageBuilder<R, C> {
content: C,
role: R,
- image_urls: Option<Vec<String>>,
+ image_urls: Option<Vec<ImageData>>,
}
impl MessageBuilder<Role, ChatMessageContent> {
@@ -91,7 +91,7 @@ impl<R> MessageBuilder<R, NoContent> {
}
impl<R, C> MessageBuilder<R, C> {
- pub fn image_urls(mut self, image_urls: Vec<String>) -> Self {
+ pub fn image_urls(mut self, image_urls: Vec<ImageData>) -> Self {
if image_urls.is_empty() {
self.image_urls = None;
self
diff --git a/rust/cloud-storage/ai/src/types/message/mod.rs b/rust/cloud-storage/ai/src/types/message/mod.rs
index e8f39cabff..4123d7434c 100644
--- a/rust/cloud-storage/ai/src/types/message/mod.rs
+++ b/rust/cloud-storage/ai/src/types/message/mod.rs
@@ -1,10 +1,14 @@
+mod base_64_image;
mod chat_message;
mod message_builder;
+mod prompt_attachments;
mod system_prompt;
+pub use base_64_image::*;
pub use chat_message::*;
pub use message_builder::*;
-pub use system_prompt::*;
+pub use prompt_attachments::*;
+pub use system_prompt::SystemPrompt;
use serde::{Deserialize, Serialize};
use strum::{AsRefStr, Display, EnumString};
diff --git a/rust/cloud-storage/ai/src/types/message/prompt_attachments.rs b/rust/cloud-storage/ai/src/types/message/prompt_attachments.rs
new file mode 100644
index 0000000000..3add66860b
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/message/prompt_attachments.rs
@@ -0,0 +1,26 @@
+use crate::traits::TextAttachment;
+
+#[derive(Debug, Clone, Default)]
+pub struct PromptAttachments(Vec<String>);
+
+impl<T> From<Vec<T>> for PromptAttachments
+where
+ T: TextAttachment + 'static,
+{
+ fn from(value: Vec<T>) -> Self {
+ Self(value.into_iter().map(|a| a.to_string()).collect())
+ }
+}
+
+impl From<&[&dyn TextAttachment]> for PromptAttachments {
+ fn from(value: &[&dyn TextAttachment]) -> Self {
+ Self(value.iter().map(|a| a.to_string()).collect())
+ }
+}
+
+impl std::ops::Deref for PromptAttachments {
+ type Target = Vec<String>;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/message/system_prompt.rs b/rust/cloud-storage/ai/src/types/message/system_prompt.rs
index 50818083c4..7a249d8d31 100644
--- a/rust/cloud-storage/ai/src/types/message/system_prompt.rs
+++ b/rust/cloud-storage/ai/src/types/message/system_prompt.rs
@@ -1,86 +1,25 @@
+use super::prompt_attachments::PromptAttachments;
use crate::tokens::{TokenCount, count_tokens};
use anyhow::Result;
-use serde::{Deserialize, Serialize};
-#[derive(Deserialize, Serialize, Clone, Eq, PartialEq)]
-pub struct PromptAttachment {
- pub id: String,
- pub file_type: String,
- pub name: String,
- pub content: String,
-}
-
-impl std::fmt::Debug for PromptAttachment {
- fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- fmt.debug_struct("PromptAttachment")
- .field("id", &self.id)
- .field("name", &self.name)
- .field("character_count", &self.content.len())
- .finish()
- }
-}
-
-#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)]
-pub(crate) struct SystemPrompt {
- pub content: String,
- pub attachments: Vec<PromptAttachment>,
+#[derive(Debug, Clone)]
+pub struct SystemPrompt {
+ pub instructions: String,
+ pub attachments: PromptAttachments,
}
impl TokenCount for SystemPrompt {
fn token_count(&self) -> Result<i64> {
- let content = self.format();
- count_tokens(&content)
+ count_tokens(&self.to_string())
}
}
-impl SystemPrompt {
- fn format_attachment(attachment: &PromptAttachment) -> String {
- format!(
- "\n<document id={} filetype={} name={}>\n{}\n</document>\n\n",
- attachment.id,
- attachment.file_type.as_str(),
- attachment.name,
- attachment.content
- )
- }
-
- /// Convers the system prompt into a string
- pub fn format(&self) -> String {
- let mut attachments_string = String::new();
+impl std::fmt::Display for SystemPrompt {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ writeln!(f, "{}", self.instructions)?;
for attachment in self.attachments.iter() {
- let attachment_string = Self::format_attachment(attachment);
- attachments_string.push_str(attachment_string.as_str());
- }
- format!("{}{}", self.content, attachments_string)
- }
-
- pub fn format_for_caching(&mut self, n_parts: usize) -> Vec<String> {
- assert!(n_parts > 0);
- // order by decreasing length
- self.attachments
- .sort_by(|a, b| b.content.len().cmp(&a.content.len()));
-
- let mut attachments = self
- .attachments
- .iter()
- .map(Self::format_attachment)
- .collect::<Vec<_>>();
- let mut parts = vec![self.content.clone()];
- parts.append(&mut attachments);
- if parts.len() <= n_parts {
- parts
- } else {
- // expect 4, have 6
- // [_,_,_,3]
- // [_,_,_,_,4,5]
-
- // [4,5]
- let excess = parts.split_off(n_parts);
- if let Some(last) = parts.last_mut() {
- // [_,_,_,345]
- last.push_str(excess.join("").as_str())
- }
- parts
+ writeln!(f, "{}", attachment)?;
}
+ Ok(())
}
}
diff --git a/rust/cloud-storage/ai/src/types/providers/openai/message.rs b/rust/cloud-storage/ai/src/types/providers/openai/message.rs
index 2b97bde403..640121ed59 100644
--- a/rust/cloud-storage/ai/src/types/providers/openai/message.rs
+++ b/rust/cloud-storage/ai/src/types/providers/openai/message.rs
@@ -8,7 +8,9 @@ use async_openai::types::{
ChatCompletionRequestUserMessageContentPart, FunctionCall, ImageDetail, ImageUrl,
};
-use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, ChatMessages, Role};
+use crate::types::{
+ AssistantMessagePart, ChatMessage, ChatMessageContent, ChatMessages, ImageData, Role,
+};
use serde::Serialize;
use std::collections::HashMap;
@@ -21,6 +23,21 @@ struct ToolResponseParseError {
parse_error: String,
}
+impl From<ImageData> for ImageUrl {
+ fn from(value: ImageData) -> Self {
+ match value {
+ ImageData::Url(url) => Self {
+ url,
+ detail: IMAGE_PROCESS_QUALITY,
+ },
+ ImageData::Bytes(base_64_image) => Self {
+ url: base_64_image.to_string(),
+ detail: IMAGE_PROCESS_QUALITY,
+ },
+ }
+ }
+}
+
impl From<ChatMessage> for Vec<ChatCompletionRequestMessage> {
fn from(value: ChatMessage) -> Self {
match value.content {
@@ -47,10 +64,7 @@ impl From<ChatMessage> for Vec<ChatCompletionRequestMessage> {
user_message_content.extend(images.into_iter().map(|url| {
ChatCompletionRequestUserMessageContentPart::ImageUrl(
ChatCompletionRequestMessageContentPartImage {
- image_url: ImageUrl {
- detail: IMAGE_PROCESS_QUALITY,
- url,
- },
+ image_url: url.into(),
},
)
}));
@@ -249,6 +263,26 @@ pub fn convert_message(
(content, image_urls)
}
};
+
+ let image_urls = match image_urls
+ .unwrap_or_default()
+ .into_iter()
+ .map(ImageData::dangerously_try_from_string)
+ .collect::<Result<Vec<_>, _>>()
+ {
+ Ok(urls) => {
+ if urls.is_empty() {
+ None
+ } else {
+ Some(urls)
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e,"failed to convert images");
+ None
+ }
+ };
+
ChatMessage {
role: Role::User,
content,
@@ -497,7 +531,9 @@ mod tests {
let original = ChatMessage {
role: Role::User,
content: ChatMessageContent::Text("What's in this image?".to_string()),
- image_urls: Some(vec!["https://example.com/image.jpg".to_string()]),
+ image_urls: Some(vec![ImageData::Url(
+ "https://example.com/image.jpg".to_string(),
+ )]),
};
let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();
@@ -667,8 +703,8 @@ mod tests {
role: Role::User,
content: ChatMessageContent::Text("Compare these images".to_string()),
image_urls: Some(vec![
- "https://example.com/image1.jpg".to_string(),
- "https://example.com/image2.jpg".to_string(),
+ ImageData::Url("https://example.com/image1.jpg".to_string()),
+ ImageData::Url("https://example.com/image2.jpg".to_string()),
]),
};
diff --git a/rust/cloud-storage/ai/src/types/providers/openai/request.rs b/rust/cloud-storage/ai/src/types/providers/openai/request.rs
index e4ac8a4a36..1671c95573 100644
--- a/rust/cloud-storage/ai/src/types/providers/openai/request.rs
+++ b/rust/cloud-storage/ai/src/types/providers/openai/request.rs
@@ -2,9 +2,8 @@ use crate::traits::Metadata;
use crate::types::ChatCompletionRequest;
use anyhow::Context;
use async_openai::types::{
- ChatCompletionRequestMessage, ChatCompletionRequestMessageContentPartText,
- ChatCompletionRequestSystemMessage, ChatCompletionRequestSystemMessageContent,
- ChatCompletionRequestSystemMessageContentPart, CreateChatCompletionRequest,
+ ChatCompletionRequestMessage, ChatCompletionRequestSystemMessage,
+ ChatCompletionRequestSystemMessageContent, CreateChatCompletionRequest,
CreateChatCompletionRequestArgs, ResponseFormat, ResponseFormatJsonSchema,
};
use schemars::{JsonSchema, schema_for};
@@ -13,21 +12,12 @@ use serde::Deserialize;
impl ChatCompletionRequest {
pub fn openai_messages(&self) -> Vec<ChatCompletionRequestMessage> {
let mut all_messages = vec![];
- let system_message_parts = self
- .system_prompt
- .clone()
- .format_for_caching(4)
- .into_iter()
- .map(|part| {
- ChatCompletionRequestSystemMessageContentPart::Text(
- ChatCompletionRequestMessageContentPartText { text: part },
- )
- })
- .collect::<Vec<_>>();
let system_message =
ChatCompletionRequestMessage::System(ChatCompletionRequestSystemMessage {
- content: ChatCompletionRequestSystemMessageContent::Array(system_message_parts),
+ content: ChatCompletionRequestSystemMessageContent::Text(
+ self.system_prompt.to_string(),
+ ),
name: None,
});
diff --git a/rust/cloud-storage/ai/src/types/providers/openai/response.rs b/rust/cloud-storage/ai/src/types/providers/openai/response.rs
index f8394b9985..9d53b81d5e 100644
--- a/rust/cloud-storage/ai/src/types/providers/openai/response.rs
+++ b/rust/cloud-storage/ai/src/types/providers/openai/response.rs
@@ -1,9 +1,8 @@
use crate::types::{ChatCompletionRequest, response::ChatStreamCompletionResponse};
use anyhow::Context;
use async_openai::types::{
- ChatCompletionRequestMessage, ChatCompletionRequestMessageContentPartText,
- ChatCompletionRequestSystemMessage, ChatCompletionRequestSystemMessageContent,
- ChatCompletionRequestSystemMessageContentPart, CreateChatCompletionRequest,
+ ChatCompletionRequestMessage, ChatCompletionRequestSystemMessage,
+ ChatCompletionRequestSystemMessageContent, CreateChatCompletionRequest,
CreateChatCompletionRequestArgs, CreateChatCompletionStreamResponse,
FinishReason as OpenAIFinishReason, ReasoningEffort,
};
@@ -15,21 +14,12 @@ impl TryFrom<ChatCompletionRequest> for CreateChatCompletionRequest {
fn try_from(value: ChatCompletionRequest) -> anyhow::Result<Self> {
let mut all_messages: Vec<ChatCompletionRequestMessage> = vec![];
// text parts are used for anthropic caching and have no effect on other models
- let system_message_parts = value
- .system_prompt
- .clone()
- .format_for_caching(4)
- .into_iter()
- .map(|part| {
- ChatCompletionRequestSystemMessageContentPart::Text(
- ChatCompletionRequestMessageContentPartText { text: part },
- )
- })
- .collect::<Vec<_>>();
let system_message =
ChatCompletionRequestMessage::System(ChatCompletionRequestSystemMessage {
- content: ChatCompletionRequestSystemMessageContent::Array(system_message_parts),
+ content: ChatCompletionRequestSystemMessageContent::Text(
+ value.system_prompt.to_string(),
+ ),
name: None,
});
diff --git a/rust/cloud-storage/ai/src/types/request.rs b/rust/cloud-storage/ai/src/types/request.rs
index 825a9b9f1e..8f4dddc627 100644
--- a/rust/cloud-storage/ai/src/types/request.rs
+++ b/rust/cloud-storage/ai/src/types/request.rs
@@ -1,12 +1,9 @@
use super::{
- message::{ChatMessage, SystemPrompt},
+ message::{Base64Image, ChatMessage, SystemPrompt},
model::Model,
};
-use crate::tokens::TokenCount;
-use crate::tokens::count_tokens;
-use anyhow::Result;
-#[derive(Clone, Debug, Eq, PartialEq)]
+#[derive(Debug, Clone)]
pub struct ChatCompletionRequest {
/// can either be openai or google
pub(crate) model: Model,
@@ -16,24 +13,35 @@ pub struct ChatCompletionRequest {
pub(crate) system_prompt: SystemPrompt,
}
-impl TokenCount for Vec<&String> {
- fn token_count(&self) -> Result<i64> {
- let mut tokens = 0;
- for message in self {
- tokens += count_tokens(message.as_str())?;
+#[derive(PartialEq, Eq, Clone)]
+pub enum ImageData {
+ Bytes(Base64Image),
+ Url(String),
+}
+
+impl ImageData {
+ /// convert image bytes into a downscaled webp
+ pub fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
+ Base64Image::compress_and_reencode(bytes).map(Self::Bytes)
+ }
+
+ pub(crate) fn dangerously_try_from_string(s: String) -> Result<Self, anyhow::Error> {
+ if s.starts_with("data:") {
+ Ok(Self::Bytes(Base64Image::dangerously_try_from_string(s)?))
+ } else {
+ Ok(Self::Url(s))
}
- Ok(tokens)
}
}
-impl TokenCount for ChatCompletionRequest {
- fn token_count(&self) -> Result<i64> {
- let mut tokens = 0;
- for message in self.messages.iter() {
- tokens += message.token_count()?;
+impl std::fmt::Debug for ImageData {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Bytes(base_64) => {
+ write!(f, "bytes {:?}", base_64)
+ }
+ Self::Url(url) => write!(f, "url {}", url),
}
- tokens += self.system_prompt.token_count()?;
- Ok(tokens)
}
}
diff --git a/rust/cloud-storage/ai/src/types/request_builder.rs b/rust/cloud-storage/ai/src/types/request_builder.rs
index 567b0a244a..76187cce23 100644
--- a/rust/cloud-storage/ai/src/types/request_builder.rs
+++ b/rust/cloud-storage/ai/src/types/request_builder.rs
@@ -1,28 +1,29 @@
-use crate::types::{
- ChatCompletionRequest, ChatMessage, Model, PromptAttachment, Role, SystemPrompt,
+use crate::{
+ traits::TextAttachment,
+ types::{ChatCompletionRequest, ChatMessage, ImageData, Model, Role, SystemPrompt},
};
#[derive(Default)]
pub struct Attachments(pub Vec<Attachment>);
-impl From<Vec<PromptAttachment>> for Attachments {
- fn from(value: Vec<PromptAttachment>) -> Self {
- Attachments(value.into_iter().map(Attachment::Text).collect())
- }
-}
-
impl From<Vec<Attachment>> for Attachments {
fn from(value: Vec<Attachment>) -> Self {
Attachments(value)
}
}
+impl From<Vec<Box<dyn TextAttachment>>> for Attachments {
+ fn from(values: Vec<Box<dyn TextAttachment>>) -> Self {
+ Attachments(values.into_iter().map(Attachment::Text).collect())
+ }
+}
+
pub enum Attachment {
/// A document, channel, project, or other thing that can be represented by text
/// These are inserted into the system prompt
- Text(PromptAttachment),
+ Text(Box<dyn TextAttachment>),
/// a base64 or static url to a supported image type
- ImageUrl(String),
+ Image(ImageData),
}
pub type NotSet = ();
@@ -84,7 +85,7 @@ impl RequestBuilder<Model, Vec<ChatMessage>, String> {
.0
.into_iter()
.map(|attachment| match attachment {
- Attachment::ImageUrl(url) => (Some(url), None),
+ Attachment::Image(data) => (Some(data), None),
Attachment::Text(text_attachment) => (None, Some(text_attachment)),
})
.collect::<(Vec<_>, Vec<_>)>();
@@ -92,8 +93,8 @@ impl RequestBuilder<Model, Vec<ChatMessage>, String> {
let image_attachments = image_attachments.into_iter().flatten().collect::<Vec<_>>();
let prompt_attachments = prompt_attachments.into_iter().flatten().collect::<Vec<_>>();
let system_prompt = SystemPrompt {
- attachments: prompt_attachments,
- content: std::mem::take(&mut self.system_prompt),
+ attachments: prompt_attachments.into(),
+ instructions: std::mem::take(&mut self.system_prompt),
};
// insert images on the last user message :)
if !image_attachments.is_empty()
@@ -166,8 +167,8 @@ impl<ChatModel, Messages, Prompt> RequestBuilder<ChatModel, Messages, Prompt> {
}
}
- pub fn add_text_attachment(mut self, attachment: impl Into<PromptAttachment>) -> Self {
- let wrapped = Attachment::Text(attachment.into());
+ pub fn add_text_attachment(mut self, attachment: Box<dyn TextAttachment>) -> Self {
+ let wrapped = Attachment::Text(attachment);
if let Some(ref mut attachments) = self.attachments {
attachments.0.push(wrapped)
} else {
@@ -176,8 +177,8 @@ impl<ChatModel, Messages, Prompt> RequestBuilder<ChatModel, Messages, Prompt> {
self
}
- pub fn add_image_attachment(mut self, image_url: String) -> Self {
- let wrapped = Attachment::ImageUrl(image_url);
+ pub fn add_image_attachment(mut self, data: ImageData) -> Self {
+ let wrapped = Attachment::Image(data);
if let Some(ref mut attachments) = self.attachments {
attachments.0.push(wrapped)
} else {
@@ -221,65 +222,7 @@ impl<ChatModel, Messages, Prompt> RequestBuilder<ChatModel, Messages, Prompt> {
#[cfg(test)]
mod test {
use super::*;
- use crate::types::{MessageBuilder, Model, PromptAttachment, Role};
- #[test]
- fn test_good_build() {
- let messages = vec![
- MessageBuilder::new()
- .content("user message 1")
- .role(Role::User)
- .build(),
- MessageBuilder::new()
- .content("assistant response")
- .role(Role::Assistant)
- .build(),
- MessageBuilder::new()
- .content("user message 2")
- .role(Role::User)
- .build(),
- ];
-
- let text_attachment = PromptAttachment {
- id: "doc1".to_string(),
- content: "Document content".to_string(),
- name: "Test Doc".to_string(),
- file_type: "md".into(),
- };
-
- let request = RequestBuilder::new()
- .system_prompt("Test system prompt".to_string())
- .messages(messages.clone())
- .model(Model::Claude35Sonnet)
- .max_tokens(1000)
- .add_text_attachment(text_attachment.clone())
- .add_image_attachment("https://example.com/image.jpg".to_string())
- .build();
-
- // Verify system prompt has text attachment
- assert_eq!(request.system_prompt.content, "Test system prompt");
- assert_eq!(request.system_prompt.attachments.len(), 1);
- assert_eq!(request.system_prompt.attachments[0].id, "doc1");
-
- // Verify model and max_tokens
- assert_eq!(request.model, Model::Claude35Sonnet);
-
- // Verify messages count
- assert_eq!(request.messages.len(), 3);
-
- // Verify last user message has image attachment
- let last_user_message = request
- .messages
- .iter()
- .rev()
- .find(|msg| msg.role == Role::User)
- .unwrap();
- assert!(last_user_message.image_urls.is_some());
- assert_eq!(last_user_message.image_urls.as_ref().unwrap().len(), 1);
- assert_eq!(
- last_user_message.image_urls.as_ref().unwrap()[0],
- "https://example.com/image.jpg"
- );
- }
+ use crate::types::{MessageBuilder, Model, Role};
#[test]
fn test_good_builder_no_options() {
@@ -296,12 +239,12 @@ mod test {
let request = RequestBuilder::new()
.system_prompt("Basic system prompt".to_string())
- .messages(messages.clone())
+ .messages(messages)
.model(Model::Claude35Sonnet)
.build();
// Verify system prompt (no attachments)
- assert_eq!(request.system_prompt.content, "Basic system prompt");
+ assert_eq!(request.system_prompt.instructions, "Basic system prompt");
assert!(request.system_prompt.attachments.is_empty());
// Verify model and default max_tokens
diff --git a/rust/cloud-storage/ai_format/Cargo.toml b/rust/cloud-storage/ai_format/Cargo.toml
index 589468a02b..1d41b9f1a5 100644
--- a/rust/cloud-storage/ai_format/Cargo.toml
+++ b/rust/cloud-storage/ai_format/Cargo.toml
@@ -6,3 +6,4 @@ version = "0.1.0"
[dependencies]
chrono = { workspace = true }
+ai = { path = "../ai" }
diff --git a/rust/cloud-storage/ai_format/src/document.rs b/rust/cloud-storage/ai_format/src/document.rs
new file mode 100644
index 0000000000..0200d9abed
--- /dev/null
+++ b/rust/cloud-storage/ai_format/src/document.rs
@@ -0,0 +1,44 @@
+use ai::traits::TextAttachment;
+
+pub struct Document {
+ pub content: String,
+ pub file_type: String,
+ pub id: String,
+ pub name: String,
+}
+
+impl std::fmt::Debug for Document {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Document")
+ .field(
+ "content",
+ &format!("content [{} chars]", self.content.len()),
+ )
+ .field("file_type", &self.file_type)
+ .field("id", &self.id)
+ .field("name", &self.name)
+ .finish()
+ }
+}
+
+impl std::fmt::Display for Document {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ r#"<document id="{}" file_type="{}" name="{}">
+ <content>
+ {}
+ </content>
+</document>"#,
+ self.id, self.file_type, self.name, self.content
+ )
+ }
+}
+
+impl TextAttachment for Document {}
+
+impl Document {
+ pub fn boxed(self) -> Box<dyn TextAttachment> {
+ Box::new(self)
+ }
+}
diff --git a/rust/cloud-storage/ai_format/src/insight_context_log.rs b/rust/cloud-storage/ai_format/src/insight_context_log.rs
new file mode 100644
index 0000000000..4cb8cf8d55
--- /dev/null
+++ b/rust/cloud-storage/ai_format/src/insight_context_log.rs
@@ -0,0 +1,27 @@
+use std::fmt::Display;
+
+pub struct InsightContextLog<T: Display> {
+ pub name: String,
+ pub metadata: Vec<(String, String)>,
+ pub content: T,
+}
+
+impl<T> Display for InsightContextLog<T>
+where
+ T: Display + Sized,
+{
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let metadata = self
+ .metadata
+ .iter()
+ .map(|(k, v)| format!("{}: {}", k, v))
+ .collect::<Vec<_>>()
+ .join(", ");
+ writeln!(f, "[{}]", self.name)?;
+ if !metadata.is_empty() {
+ writeln!(f, "{}", metadata)?;
+ }
+ writeln!(f, "{}", self.content)?;
+ writeln!(f, "[END {}]", self.name)
+ }
+}
diff --git a/rust/cloud-storage/ai_format/src/lib.rs b/rust/cloud-storage/ai_format/src/lib.rs
index 2e75855f55..556cfce998 100644
--- a/rust/cloud-storage/ai_format/src/lib.rs
+++ b/rust/cloud-storage/ai_format/src/lib.rs
@@ -1,6 +1,3 @@
-pub mod traits;
-pub mod types;
-mod util;
-
-pub use traits::AiFormat;
-pub use util::*;
+pub mod document;
+pub mod insight_context_log;
+pub mod util;
diff --git a/rust/cloud-storage/ai_format/src/traits.rs b/rust/cloud-storage/ai_format/src/traits.rs
deleted file mode 100644
index 804af51798..0000000000
--- a/rust/cloud-storage/ai_format/src/traits.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub trait AiFormat {
- fn ai_format(self) -> impl std::fmt::Display;
-}
diff --git a/rust/cloud-storage/ai_format/src/types.rs b/rust/cloud-storage/ai_format/src/types.rs
deleted file mode 100644
index 59cba88a03..0000000000
--- a/rust/cloud-storage/ai_format/src/types.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-// this is a good pattern that we are not yet ready for
-// use crate::traits::AiFormat;
-
-// pub struct DocumentFormat {
-// pub content: String,
-// pub id: String,
-// pub name: String,
-// pub file_type: String,
-// }
-
-// impl AiFormat for DocumentFormat {
-// fn ai_format(self) -> impl std::fmt::Display {
-// format!(
-// "<document name={} id={} file_type={}>\n{}\n</document>",
-// self.name, self.id, self.file_type, self.content
-// )
-// }
-// }
diff --git a/rust/cloud-storage/ai_format/src/util.rs b/rust/cloud-storage/ai_format/src/util.rs
index 29b995ddd4..18b37a62d9 100644
--- a/rust/cloud-storage/ai_format/src/util.rs
+++ b/rust/cloud-storage/ai_format/src/util.rs
@@ -16,11 +16,6 @@ pub fn truncate<T: Display>(v: T, limit: usize) -> String {
pub struct Indent<T: Sized>(pub T, pub usize);
pub struct Truncate<T: Sized>(pub T, pub usize);
-pub struct InsightContextLog<T: Display> {
- pub name: String,
- pub metadata: Vec<(String, String)>,
- pub content: T,
-}
impl<T> Display for Indent<T>
where
@@ -49,29 +44,10 @@ where
}
}
-impl<T> Display for InsightContextLog<T>
-where
- T: Display + Sized,
-{
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let metadata = self
- .metadata
- .iter()
- .map(|(k, v)| format!("{}: {}", k, v))
- .collect::<Vec<_>>()
- .join(", ");
- writeln!(f, "[{}]", self.name)?;
- if !metadata.is_empty() {
- writeln!(f, "{}", metadata)?;
- }
- writeln!(f, "{}", self.content)?;
- writeln!(f, "[END {}]", self.name)
- }
-}
-
#[cfg(test)]
mod test {
use super::*;
+ use crate::insight_context_log::InsightContextLog;
#[test]
fn test_truncate() {
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index ce91ae2596..bf3cd931c2 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -37,7 +37,7 @@ tokio.workspace = true
tracing.workspace = true
utoipa.workspace = true
uuid.workspace = true
-
+ai_format= { path = "../ai_format" }
anthropic = { path = "../anthropic"}
[dev-dependencies]
diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
index e41c56e3df..7d3f877d8e 100644
--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
@@ -2,7 +2,8 @@ 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, PromptAttachment, RequestBuilder};
+use ai::types::{MessageBuilder, RequestBuilder};
+use ai_format::document::Document;
use anyhow::Error;
use async_trait::async_trait;
use model::document::FileType;
@@ -80,12 +81,15 @@ pub async fn generate_patches(
.max_tokens(32_000)
.system_prompt(PROMPT)
.model(REWRITE_MODEL)
- .add_text_attachment(PromptAttachment {
- content: markdown_text,
- file_type: "md".into(),
- id: request.markdown_file_id,
- name: file_name,
- })
+ .add_text_attachment(
+ Document {
+ content: markdown_text,
+ file_type: "md".into(),
+ id: request.markdown_file_id,
+ name: file_name,
+ }
+ .boxed(),
+ )
.messages(vec![
MessageBuilder::new()
.content(request.instructions)
diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs
index 9863419fce..6327b61a89 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs
@@ -2,7 +2,8 @@ use crate::api::{
context::AppState,
extractors::{ChannelId, ChannelMember},
};
-use ai_format::{Indent, InsightContextLog};
+use ai_format::insight_context_log::InsightContextLog;
+use ai_format::util::Indent;
use axum::{
extract::{Path, Query, State},
http::StatusCode,
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index b859bbac0f..478acfe709 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -98,6 +98,7 @@ unfurl_service = { path = "../unfurl_service" }
utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
uuid = { workspace = true }
+ai_format = { path = "../ai_format" }
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/document_cognition_service/schemas/tools.json b/rust/cloud-storage/document_cognition_service/schemas/tools.json
index 11479ef1f4..a9cfc9d996 100644
--- a/rust/cloud-storage/document_cognition_service/schemas/tools.json
+++ b/rust/cloud-storage/document_cognition_service/schemas/tools.json
@@ -1,164 +1,5 @@
{
"schemas": [
- {
- "name": "ListDocuments",
- "inputSchema": {
- "additionalProperties": false,
- "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
- "properties": {
- "exhaustiveSearch": {
- "additionalProperties": false,
- "default": false,
- "description": "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.",
- "type": "boolean"
- },
- "fileTypes": {
- "additionalProperties": false,
- "description": "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": [
- "array",
- "null"
- ]
- },
- "minAccessLevel": {
- "additionalProperties": false,
- "description": "Minimum access level required. Defaults to 'view' if not specified.",
- "enum": [
- "view",
- "comment",
- "edit",
- "owner",
- null
- ],
- "type": [
- "string",
- "null"
- ]
- },
- "pageOffset": {
- "additionalProperties": false,
- "default": 0,
- "description": "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.",
- "format": "int64",
- "type": "integer"
- },
- "pageSize": {
- "additionalProperties": false,
- "default": 50,
- "description": "Number of results per page. Max is 100, default is 50. Use smaller values for focused results.",
- "format": "int64",
- "type": "integer"
- }
- },
- "required": [
- "exhaustiveSearch",
- "fileTypes",
- "minAccessLevel",
- "pageOffset",
- "pageSize"
- ],
- "title": "ListDocuments",
- "type": "object"
- },
- "outputSchema": {
- "properties": {
- "results": {
- "description": "The list results (truncated to `results_returned` limit if applicable)",
- "items": {
- "properties": {
- "access_level": {
- "description": "The user's access level to this document",
- "enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ],
- "type": "string"
- },
- "created_at": {
- "description": "When the document was created",
- "format": "date-time",
- "type": "string"
- },
- "deleted_at": {
- "description": "When the document was deleted (null if not deleted)",
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- },
- "document_id": {
- "description": "The document id",
- "type": "string"
- },
- "document_name": {
- "description": "The document name",
- "type": "string"
- },
- "file_type": {
- "description": "The file type of the document",
- "type": [
- "string",
- "null"
- ]
- },
- "owner": {
- "description": "The owner of the document",
- "type": "string"
- },
- "project_id": {
- "description": "The project id containing the document",
- "type": [
- "string",
- "null"
- ]
- },
- "updated_at": {
- "description": "When the document was last updated",
- "format": "date-time",
- "type": "string"
- }
- },
- "required": [
- "document_id",
- "document_name",
- "owner",
- "created_at",
- "updated_at",
- "access_level"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "resultsReturned": {
- "description": "The number of results returned",
- "format": "uint",
- "minimum": 0,
- "type": "integer"
- },
- "totalResults": {
- "description": "Total number of results found",
- "format": "uint",
- "minimum": 0,
- "type": "integer"
- }
- },
- "required": [
- "results",
- "totalResults",
- "resultsReturned"
- ],
- "title": "ListDocumentsResponse",
- "type": "object"
- }
- },
{
"name": "ListEmails",
"inputSchema": {
@@ -574,512 +415,152 @@
}
},
{
- "name": "Read",
+ "name": "UnifiedSearch",
"inputSchema": {
"additionalProperties": false,
- "description": "Read content by ID(s). Supports reading documents, channels, chats, and emails by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s).\n Channel transcripts only include 300 messages. Use 'messages_since' to see messages in a different time window.",
+ "description": "Universal search across all content types (documents, emails, AI conversations, chat/slack threads/channels, projects aka folders). This tool will return broad metadata from successful results and/or content matches. Use the Read tool next to read the results from those matches. Only ever refer to documents by name or with a document mention. Never state the id of the document in plaintext. User's are presented with the results of this tool as a UI element so there is no need to enumerate the information found from this tool.",
"properties": {
- "contentType": {
+ "exhaustiveSearch": {
"additionalProperties": false,
- "description": "The type of content to read. Choose based on the type of content you want to retrieve.",
- "enum": [
- "document",
- "channel",
- "channel-message",
- "chat-thread",
- "chat-message",
- "email-thread",
- "email-message",
- "project"
- ],
- "type": "string"
+ "default": true,
+ "description": "Exhaustive search across all results matching the query. Defaults to true. Use false when the user only requires a limitied subset of results to answer the question",
+ "type": "boolean"
},
- "ids": {
+ "pageOffset": {
"additionalProperties": false,
- "description": "ID(s) of the content to read. IMPORTANT: document, channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
+ "default": 0,
+ "description": "Page offset. Default is 0. Use a higher offset to page through results intelligently. Set exhaustive_search to true to get all results.",
+ "format": "int64",
+ "type": "integer"
},
- "messagesSince": {
+ "pageSize": {
"additionalProperties": false,
- "description": "A local datetime of the earliest message to include in a channel transcript ex: 2025-11-25 12:00:09 EST, only applicable to channels",
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "contentType",
- "ids",
- "messagesSince"
- ],
- "title": "Read",
- "type": "object"
- },
- "outputSchema": {
- "properties": {
- "content": {
- "oneOf": [
- {
+ "default": 10,
+ "description": "Search count per search type (i.e. applies separately to each of documents, emails, ai_conversations, chats, projects). Max is 100. Default is 10. Does not apply when exhaustive_search is set to true.",
+ "format": "int64",
+ "type": "integer"
+ },
+ "request": {
+ "additionalProperties": false,
+ "description": "Aggregated search request, see individual fields for details",
+ "properties": {
+ "filters": {
+ "additionalProperties": false,
+ "description": "Search filters for various kinds of items. Set the entire filters property as `null` if you do not have specific filters for a given type, e.g. bcc for email filters.",
"properties": {
- "documents": {
- "items": {
- "properties": {
- "content": {
+ "channel": {
+ "additionalProperties": false,
+ "description": "Channel filters. `null` to not filter channels searched over.",
+ "properties": {
+ "channel_ids": {
+ "additionalProperties": false,
+ "description": "Channel IDs to search within. Examples: ['general']. Empty to search all accessible channels.",
+ "items": {
+ "additionalProperties": false,
"type": "string"
},
- "documentId": {
+ "type": "array"
+ },
+ "mentions": {
+ "additionalProperties": false,
+ "description": "Channel user mentions to search for. Examples: ['@username']. Empty if not filtering by mentions.",
+ "items": {
+ "additionalProperties": false,
"type": "string"
},
- "metadata": {
- "properties": {
- "deleted": {
- "type": "boolean"
- },
- "documentName": {
- "type": "string"
- },
- "fileType": {
- "type": [
- "string",
- "null"
- ]
- },
- "owner": {
- "type": "string"
- },
- "projectId": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "documentName",
- "owner",
- "deleted"
- ],
- "type": "object"
- }
+ "type": "array"
},
- "required": [
- "documentId",
- "content",
- "metadata"
- ],
- "type": "object"
+ "org_id": {
+ "additionalProperties": false,
+ "description": "Channel organization ID to search within. Empty to ignore organization filtering.",
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "sender_ids": {
+ "additionalProperties": false,
+ "description": "Sender IDs to search within. Examples: ['user1']. Empty to search all accessible senders.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "thread_ids": {
+ "additionalProperties": false,
+ "description": "Channel thread IDs to search within. Examples: ['thread123']. Empty to search all threads.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": "array"
+ }
},
- "type": "array"
- },
- "type": {
- "const": "documents",
- "type": "string"
- }
- },
- "required": [
- "type",
- "documents"
- ],
- "type": "object"
- },
- {
- "properties": {
- "channel_id": {
- "type": "string"
- },
- "channel_name": {
+ "required": [
+ "channel_ids",
+ "mentions",
+ "org_id",
+ "sender_ids",
+ "thread_ids"
+ ],
"type": [
- "string",
+ "object",
"null"
]
},
- "transcript": {
- "type": "string"
- },
- "type": {
- "const": "channel",
- "type": "string"
- }
- },
- "required": [
- "type",
- "channel_id",
- "transcript"
- ],
- "type": "object"
- },
- {
- "properties": {
- "conversation": {
- "items": {
- "properties": {
- "chat_id": {
+ "chat": {
+ "additionalProperties": false,
+ "description": "Chat filters. `null` to not filter chats searched over.",
+ "properties": {
+ "chat_ids": {
+ "additionalProperties": false,
+ "description": "Chat ids to search over. Examples: ['chat1'], ['chat1', 'chat2']. When provided, chat search will only match results on these chats. Empty to search all accessible chats.",
+ "items": {
+ "additionalProperties": false,
"type": "string"
},
- "messages": {
- "items": {
- "properties": {
- "attachment_summaries": {
- "items": {
- "oneOf": [
- {
- "additionalProperties": false,
- "properties": {
- "Summary": {
- "properties": {
- "created_at": {
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- },
- "document_id": {
- "type": "string"
- },
- "id": {
- "type": [
- "string",
- "null"
- ]
- },
- "summary": {
- "type": "string"
- },
- "version_id": {
- "type": "string"
- }
- },
- "required": [
- "document_id",
- "summary",
- "version_id"
- ],
- "type": "object"
- }
- },
- "required": [
- "Summary"
- ],
- "type": "object"
- },
- {
- "additionalProperties": false,
- "properties": {
- "NoSummary": {
- "properties": {
- "document_id": {
- "type": "string"
- }
- },
- "required": [
- "document_id"
- ],
- "type": "object"
- }
- },
- "required": [
- "NoSummary"
- ],
- "type": "object"
- }
- ]
- },
- "type": "array"
- },
- "content": {
- "type": "string"
- },
- "date": {
- "format": "date-time",
- "type": "string"
- }
- },
- "required": [
- "content",
- "date",
- "attachment_summaries"
- ],
- "type": "object"
- },
- "type": "array"
+ "type": "array"
+ },
+ "owners": {
+ "additionalProperties": false,
+ "description": "Filter by chat owner. Examples: ['macro|[email protected]'], ['macro|[email protected]', 'macro|[email protected]']. Empty to search all owners.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
},
- "title": {
+ "type": "array"
+ },
+ "project_ids": {
+ "additionalProperties": false,
+ "description": "A list of project ids to search within. Examples: ['project1']. Empty to ignore project filtering.",
+ "items": {
+ "additionalProperties": false,
"type": "string"
- }
+ },
+ "type": "array"
},
- "required": [
- "chat_id",
- "title",
- "messages"
- ],
- "type": "object"
+ "role": {
+ "additionalProperties": false,
+ "description": "Chat message roles to search. Examples: ['user'], ['assistant']. Empty to search all roles.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": "array"
+ }
},
- "type": "array"
- },
- "type": {
- "const": "chat",
- "type": "string"
- }
- },
- "required": [
- "type",
- "conversation"
- ],
- "type": "object"
- },
- {
- "properties": {
- "messages": {
- "items": {
- "properties": {
- "bcc": {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "cc": {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "content": {
- "type": "string"
- },
- "messageId": {
- "type": "string"
- },
- "recipients": {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "sender": {
- "type": "string"
- },
- "sentAt": {
- "format": "date-time",
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "messageId",
- "sender",
- "recipients",
- "cc",
- "bcc",
- "content"
- ],
- "type": "object"
- },
- "type": "array"
- },
- "subject": {
- "type": [
- "string",
- "null"
- ]
- },
- "thread_id": {
- "type": "string"
- },
- "type": {
- "const": "email",
- "type": "string"
- }
- },
- "required": [
- "type",
- "thread_id",
- "messages"
- ],
- "type": "object"
- },
- {
- "properties": {
- "formatted_preview": {
- "type": "string"
- },
- "type": {
- "const": "itemPreviews",
- "type": "string"
- }
- },
- "required": [
- "type",
- "formatted_preview"
- ],
- "type": "object"
- }
- ]
- }
- },
- "required": [
- "content"
- ],
- "title": "ReadResponse",
- "type": "object"
- }
- },
- {
- "name": "UnifiedSearch",
- "inputSchema": {
- "additionalProperties": false,
- "description": "Universal search across all content types (documents, emails, AI conversations, chat/slack threads/channels, projects aka folders). This tool will return broad metadata from successful results and/or content matches. Use the Read tool next to read the results from those matches. Only ever refer to documents by name or with a document mention. Never state the id of the document in plaintext. User's are presented with the results of this tool as a UI element so there is no need to enumerate the information found from this tool.",
- "properties": {
- "exhaustiveSearch": {
- "additionalProperties": false,
- "default": true,
- "description": "Exhaustive search across all results matching the query. Defaults to true. Use false when the user only requires a limitied subset of results to answer the question",
- "type": "boolean"
- },
- "pageOffset": {
- "additionalProperties": false,
- "default": 0,
- "description": "Page offset. Default is 0. Use a higher offset to page through results intelligently. Set exhaustive_search to true to get all results.",
- "format": "int64",
- "type": "integer"
- },
- "pageSize": {
- "additionalProperties": false,
- "default": 10,
- "description": "Search count per search type (i.e. applies separately to each of documents, emails, ai_conversations, chats, projects). Max is 100. Default is 10. Does not apply when exhaustive_search is set to true.",
- "format": "int64",
- "type": "integer"
- },
- "request": {
- "additionalProperties": false,
- "description": "Aggregated search request, see individual fields for details",
- "properties": {
- "filters": {
- "additionalProperties": false,
- "description": "Search filters for various kinds of items. Set the entire filters property as `null` if you do not have specific filters for a given type, e.g. bcc for email filters.",
- "properties": {
- "channel": {
- "additionalProperties": false,
- "description": "Channel filters. `null` to not filter channels searched over.",
- "properties": {
- "channel_ids": {
- "additionalProperties": false,
- "description": "Channel IDs to search within. Examples: ['general']. Empty to search all accessible channels.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "mentions": {
- "additionalProperties": false,
- "description": "Channel user mentions to search for. Examples: ['@username']. Empty if not filtering by mentions.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "org_id": {
- "additionalProperties": false,
- "description": "Channel organization ID to search within. Empty to ignore organization filtering.",
- "format": "int64",
- "type": [
- "integer",
- "null"
- ]
- },
- "sender_ids": {
- "additionalProperties": false,
- "description": "Sender IDs to search within. Examples: ['user1']. Empty to search all accessible senders.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "thread_ids": {
- "additionalProperties": false,
- "description": "Channel thread IDs to search within. Examples: ['thread123']. Empty to search all threads.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- }
- },
- "required": [
- "channel_ids",
- "mentions",
- "org_id",
- "sender_ids",
- "thread_ids"
- ],
- "type": [
- "object",
- "null"
- ]
- },
- "chat": {
- "additionalProperties": false,
- "description": "Chat filters. `null` to not filter chats searched over.",
- "properties": {
- "chat_ids": {
- "additionalProperties": false,
- "description": "Chat ids to search over. Examples: ['chat1'], ['chat1', 'chat2']. When provided, chat search will only match results on these chats. Empty to search all accessible chats.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "owners": {
- "additionalProperties": false,
- "description": "Filter by chat owner. Examples: ['macro|[email protected]'], ['macro|[email protected]', 'macro|[email protected]']. Empty to search all owners.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "project_ids": {
- "additionalProperties": false,
- "description": "A list of project ids to search within. Examples: ['project1']. Empty to ignore project filtering.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- },
- "role": {
- "additionalProperties": false,
- "description": "Chat message roles to search. Examples: ['user'], ['assistant']. Empty to search all roles.",
- "items": {
- "additionalProperties": false,
- "type": "string"
- },
- "type": "array"
- }
- },
- "required": [
- "chat_ids",
- "owners",
- "project_ids",
- "role"
- ],
- "type": [
- "object",
- "null"
- ]
+ "required": [
+ "chat_ids",
+ "owners",
+ "project_ids",
+ "role"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
},
"document": {
"additionalProperties": false,
@@ -2008,310 +1489,829 @@
"description": "The type of channel",
"type": "string"
},
- "id": {
- "description": "Standardized fields that all item types will share.\nThese field names are being aligned across all item types\nfor consistency in our data model.",
- "format": "uuid",
+ "id": {
+ "description": "Standardized fields that all item types will share.\nThese field names are being aligned across all item types\nfor consistency in our data model.",
+ "format": "uuid",
+ "type": "string"
+ },
+ "metadata": {
+ "description": "Metadata from the database. None if the channel doesn't exist in the database.",
+ "properties": {
+ "created_at": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "interacted_at": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "updated_at": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "viewed_at": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "created_at",
+ "updated_at"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
+ "owner_id": {
+ "description": "we don't store this for channels atm but keeping it here for consistency",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "const": "channel",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "channel_type",
+ "channel_id",
+ "channel_message_search_results"
+ ],
+ "type": "object"
+ },
+ {
+ "description": "ProjectSearchResponseItem object with project metadata we fetch from macrodb. we don't store these\ntimestamps in opensearch as they would require us to update the project record\nevery time the project updates (specifically for updated_at and viewed_at)",
+ "properties": {
+ "created_at": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "id": {
+ "description": "Standardized fields that all item types will share.\nThese field names are being aligned across all item types\nfor consistency in our data model.",
+ "format": "uuid",
+ "type": "string"
+ },
+ "metadata": {
+ "description": "Metadata from the database. None if the project doesn't exist in the database.",
+ "properties": {
+ "created_at": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "deleted_at": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "parent_project_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "updated_at": {
+ "format": "int64",
+ "type": "integer"
+ },
+ "viewed_at": {
+ "format": "int64",
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "created_at",
+ "updated_at"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "owner_id": {
+ "type": "string"
+ },
+ "project_search_results": {
+ "items": {
+ "properties": {
+ "highlight": {
+ "properties": {
+ "bcc": {
+ "description": "The highlight match on the bcc (email only)",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "cc": {
+ "description": "The highlight match on the cc (email only)",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "content": {
+ "description": "The highlight match on the content field",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "name": {
+ "description": "The highlight match on the name field",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "recipients": {
+ "description": "The highlight match on the recipients (email only)",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "sender": {
+ "description": "The highlight match on the sender (email only)",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "user_id": {
+ "description": "The highlight match on the user (owner) of the entity",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "type": "object"
+ },
+ "score": {
+ "description": "The score of the result",
+ "format": "double",
+ "type": [
+ "number",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "highlight"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "project",
+ "type": "string"
+ },
+ "updated_at": {
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "name",
+ "owner_id",
+ "updated_at",
+ "created_at",
+ "project_search_results"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "resultsReturned": {
+ "description": "the number of results returned",
+ "format": "uint",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "totalResults": {
+ "description": "total number of results from search",
+ "format": "uint",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "results",
+ "totalResults",
+ "resultsReturned"
+ ],
+ "type": "object"
+ },
+ "responseSchema": {
+ "description": "The JSON schema for the response so the LLM can understand it"
+ }
+ },
+ "required": [
+ "response",
+ "responseSchema"
+ ],
+ "title": "UnifiedSearchResponseOutput",
+ "type": "object"
+ }
+ },
+ {
+ "name": "ListDocuments",
+ "inputSchema": {
+ "additionalProperties": false,
+ "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "properties": {
+ "exhaustiveSearch": {
+ "additionalProperties": false,
+ "default": false,
+ "description": "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.",
+ "type": "boolean"
+ },
+ "fileTypes": {
+ "additionalProperties": false,
+ "description": "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "minAccessLevel": {
+ "additionalProperties": false,
+ "description": "Minimum access level required. Defaults to 'view' if not specified.",
+ "enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner",
+ null
+ ],
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "pageOffset": {
+ "additionalProperties": false,
+ "default": 0,
+ "description": "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.",
+ "format": "int64",
+ "type": "integer"
+ },
+ "pageSize": {
+ "additionalProperties": false,
+ "default": 50,
+ "description": "Number of results per page. Max is 100, default is 50. Use smaller values for focused results.",
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "exhaustiveSearch",
+ "fileTypes",
+ "minAccessLevel",
+ "pageOffset",
+ "pageSize"
+ ],
+ "title": "ListDocuments",
+ "type": "object"
+ },
+ "outputSchema": {
+ "properties": {
+ "results": {
+ "description": "The list results (truncated to `results_returned` limit if applicable)",
+ "items": {
+ "properties": {
+ "access_level": {
+ "description": "The user's access level to this document",
+ "enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ],
+ "type": "string"
+ },
+ "created_at": {
+ "description": "When the document was created",
+ "format": "date-time",
+ "type": "string"
+ },
+ "deleted_at": {
+ "description": "When the document was deleted (null if not deleted)",
+ "format": "date-time",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "document_id": {
+ "description": "The document id",
+ "type": "string"
+ },
+ "document_name": {
+ "description": "The document name",
+ "type": "string"
+ },
+ "file_type": {
+ "description": "The file type of the document",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "owner": {
+ "description": "The owner of the document",
+ "type": "string"
+ },
+ "project_id": {
+ "description": "The project id containing the document",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "updated_at": {
+ "description": "When the document was last updated",
+ "format": "date-time",
+ "type": "string"
+ }
+ },
+ "required": [
+ "document_id",
+ "document_name",
+ "owner",
+ "created_at",
+ "updated_at",
+ "access_level"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "resultsReturned": {
+ "description": "The number of results returned",
+ "format": "uint",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "totalResults": {
+ "description": "Total number of results found",
+ "format": "uint",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "results",
+ "totalResults",
+ "resultsReturned"
+ ],
+ "title": "ListDocumentsResponse",
+ "type": "object"
+ }
+ },
+ {
+ "name": "MarkdownRewrite",
+ "inputSchema": {
+ "additionalProperties": false,
+ "description": "Instruct an agent to edit a markdown file identified by an id.\n This tool should be used when the user include a markdown file in context and requests a revision or edit to that file",
+ "properties": {
+ "instructions": {
+ "additionalProperties": false,
+ "description": "Instructions for the revision agent to follow to edit the markdown. These instructions will be provided by the user.",
+ "type": "string"
+ },
+ "markdown_file_id": {
+ "additionalProperties": false,
+ "description": "The markdown file id to target for editing. This file id will be in your context and labeled as a markdown (md) document",
+ "type": "string"
+ }
+ },
+ "required": [
+ "instructions",
+ "markdown_file_id"
+ ],
+ "title": "MarkdownRewrite",
+ "type": "object"
+ },
+ "outputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "diffs": {
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "markdown_text": {
+ "type": "string"
+ },
+ "node_key": {
+ "type": "string"
+ },
+ "operation": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "operation",
+ "node_key",
+ "markdown_text"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "diffs"
+ ],
+ "title": "AIDiffResponse",
+ "type": "object"
+ }
+ },
+ {
+ "name": "Read",
+ "inputSchema": {
+ "additionalProperties": false,
+ "description": "Read content by ID(s). Supports reading documents, channels, chats, and emails by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s).\n Channel transcripts only include 300 messages. Use 'messages_since' to see messages in a different time window.",
+ "properties": {
+ "contentType": {
+ "additionalProperties": false,
+ "description": "The type of content to read. Choose based on the type of content you want to retrieve.",
+ "enum": [
+ "document",
+ "channel",
+ "channel-message",
+ "chat-thread",
+ "chat-message",
+ "email-thread",
+ "email-message",
+ "project"
+ ],
+ "type": "string"
+ },
+ "ids": {
+ "additionalProperties": false,
+ "description": "ID(s) of the content to read. IMPORTANT: document, channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "messagesSince": {
+ "additionalProperties": false,
+ "description": "A local datetime of the earliest message to include in a channel transcript ex: 2025-11-25 12:00:09 EST, only applicable to channels",
+ "format": "date-time",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "contentType",
+ "ids",
+ "messagesSince"
+ ],
+ "title": "Read",
+ "type": "object"
+ },
+ "outputSchema": {
+ "properties": {
+ "content": {
+ "oneOf": [
+ {
+ "properties": {
+ "documents": {
+ "items": {
+ "properties": {
+ "content": {
+ "type": "string"
+ },
+ "documentId": {
"type": "string"
},
"metadata": {
- "description": "Metadata from the database. None if the channel doesn't exist in the database.",
"properties": {
- "created_at": {
- "format": "int64",
- "type": "integer"
+ "deleted": {
+ "type": "boolean"
},
- "interacted_at": {
- "format": "int64",
+ "documentName": {
+ "type": "string"
+ },
+ "fileType": {
"type": [
- "integer",
+ "string",
"null"
]
},
- "updated_at": {
- "format": "int64",
- "type": "integer"
+ "owner": {
+ "type": "string"
},
- "viewed_at": {
- "format": "int64",
+ "projectId": {
"type": [
- "integer",
+ "string",
"null"
]
}
},
"required": [
- "created_at",
- "updated_at"
+ "documentName",
+ "owner",
+ "deleted"
],
- "type": [
- "object",
- "null"
- ]
- },
- "owner_id": {
- "description": "we don't store this for channels atm but keeping it here for consistency",
- "type": [
- "string",
- "null"
- ]
- },
- "type": {
- "const": "channel",
- "type": "string"
+ "type": "object"
}
},
"required": [
- "type",
- "id",
- "channel_type",
- "channel_id",
- "channel_message_search_results"
+ "documentId",
+ "content",
+ "metadata"
],
"type": "object"
},
- {
- "description": "ProjectSearchResponseItem object with project metadata we fetch from macrodb. we don't store these\ntimestamps in opensearch as they would require us to update the project record\nevery time the project updates (specifically for updated_at and viewed_at)",
+ "type": "array"
+ },
+ "type": {
+ "const": "documents",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "documents"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "channel_id": {
+ "type": "string"
+ },
+ "channel_name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "transcript": {
+ "type": "string"
+ },
+ "type": {
+ "const": "channel",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "channel_id",
+ "transcript"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "conversation": {
+ "items": {
"properties": {
- "created_at": {
- "format": "int64",
- "type": "integer"
- },
- "id": {
- "description": "Standardized fields that all item types will share.\nThese field names are being aligned across all item types\nfor consistency in our data model.",
- "format": "uuid",
- "type": "string"
- },
- "metadata": {
- "description": "Metadata from the database. None if the project doesn't exist in the database.",
- "properties": {
- "created_at": {
- "format": "int64",
- "type": "integer"
- },
- "deleted_at": {
- "format": "int64",
- "type": [
- "integer",
- "null"
- ]
- },
- "parent_project_id": {
- "type": [
- "string",
- "null"
- ]
- },
- "updated_at": {
- "format": "int64",
- "type": "integer"
- },
- "viewed_at": {
- "format": "int64",
- "type": [
- "integer",
- "null"
- ]
- }
- },
- "required": [
- "created_at",
- "updated_at"
- ],
- "type": [
- "object",
- "null"
- ]
- },
- "name": {
- "type": "string"
- },
- "owner_id": {
+ "chat_id": {
"type": "string"
},
- "project_search_results": {
+ "messages": {
"items": {
"properties": {
- "highlight": {
- "properties": {
- "bcc": {
- "description": "The highlight match on the bcc (email only)",
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "cc": {
- "description": "The highlight match on the cc (email only)",
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "content": {
- "description": "The highlight match on the content field",
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "name": {
- "description": "The highlight match on the name field",
- "type": [
- "string",
- "null"
- ]
- },
- "recipients": {
- "description": "The highlight match on the recipients (email only)",
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- "sender": {
- "description": "The highlight match on the sender (email only)",
- "type": [
- "string",
- "null"
- ]
- },
- "user_id": {
- "description": "The highlight match on the user (owner) of the entity",
- "type": [
- "string",
- "null"
- ]
- }
+ "attachment_summaries": {
+ "items": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "Summary": {
+ "properties": {
+ "created_at": {
+ "format": "date-time",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "document_id": {
+ "type": "string"
+ },
+ "id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "summary": {
+ "type": "string"
+ },
+ "version_id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "document_id",
+ "summary",
+ "version_id"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "Summary"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "NoSummary": {
+ "properties": {
+ "document_id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "document_id"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "NoSummary"
+ ],
+ "type": "object"
+ }
+ ]
},
- "type": "object"
+ "type": "array"
},
- "score": {
- "description": "The score of the result",
- "format": "double",
- "type": [
- "number",
- "null"
- ]
+ "content": {
+ "type": "string"
+ },
+ "date": {
+ "format": "date-time",
+ "type": "string"
}
},
"required": [
- "highlight"
+ "content",
+ "date",
+ "attachment_summaries"
],
"type": "object"
},
"type": "array"
},
- "type": {
- "const": "project",
+ "title": {
"type": "string"
- },
- "updated_at": {
- "format": "int64",
- "type": "integer"
}
},
"required": [
- "type",
- "id",
- "name",
- "owner_id",
- "updated_at",
- "created_at",
- "project_search_results"
+ "chat_id",
+ "title",
+ "messages"
],
"type": "object"
- }
- ]
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "chat",
+ "type": "string"
+ }
},
- "type": "array"
- },
- "resultsReturned": {
- "description": "the number of results returned",
- "format": "uint",
- "minimum": 0,
- "type": "integer"
+ "required": [
+ "type",
+ "conversation"
+ ],
+ "type": "object"
},
- "totalResults": {
- "description": "total number of results from search",
- "format": "uint",
- "minimum": 0,
- "type": "integer"
- }
- },
- "required": [
- "results",
- "totalResults",
- "resultsReturned"
- ],
- "type": "object"
- },
- "responseSchema": {
- "description": "The JSON schema for the response so the LLM can understand it"
- }
- },
- "required": [
- "response",
- "responseSchema"
- ],
- "title": "UnifiedSearchResponseOutput",
- "type": "object"
- }
- },
- {
- "name": "MarkdownRewrite",
- "inputSchema": {
- "additionalProperties": false,
- "description": "Instruct an agent to edit a markdown file identified by an id.\n This tool should be used when the user include a markdown file in context and requests a revision or edit to that file",
- "properties": {
- "instructions": {
- "additionalProperties": false,
- "description": "Instructions for the revision agent to follow to edit the markdown. These instructions will be provided by the user.",
- "type": "string"
- },
- "markdown_file_id": {
- "additionalProperties": false,
- "description": "The markdown file id to target for editing. This file id will be in your context and labeled as a markdown (md) document",
- "type": "string"
- }
- },
- "required": [
- "instructions",
- "markdown_file_id"
- ],
- "title": "MarkdownRewrite",
- "type": "object"
- },
- "outputSchema": {
- "additionalProperties": false,
- "properties": {
- "diffs": {
- "items": {
- "additionalProperties": false,
- "properties": {
- "markdown_text": {
- "type": "string"
- },
- "node_key": {
- "type": "string"
+ {
+ "properties": {
+ "messages": {
+ "items": {
+ "properties": {
+ "bcc": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "cc": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "content": {
+ "type": "string"
+ },
+ "messageId": {
+ "type": "string"
+ },
+ "recipients": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "sender": {
+ "type": "string"
+ },
+ "sentAt": {
+ "format": "date-time",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "messageId",
+ "sender",
+ "recipients",
+ "cc",
+ "bcc",
+ "content"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "subject": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "type": {
+ "const": "email",
+ "type": "string"
+ }
},
- "operation": {
- "type": "string"
- }
+ "required": [
+ "type",
+ "thread_id",
+ "messages"
+ ],
+ "type": "object"
},
- "required": [
- "operation",
- "node_key",
- "markdown_text"
- ],
- "type": "object"
- },
- "type": "array"
+ {
+ "properties": {
+ "formatted_preview": {
+ "type": "string"
+ },
+ "type": {
+ "const": "itemPreviews",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "formatted_preview"
+ ],
+ "type": "object"
+ }
+ ]
}
},
"required": [
- "diffs"
+ "content"
],
- "title": "AIDiffResponse",
+ "title": "ReadResponse",
"type": "object"
}
},
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
index 5f2b3b5e1b..259e0790f5 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
@@ -339,7 +339,7 @@ pub async fn handle_send_chat_message(
let StreamChatResponse { new_messages } = stream_chat_response(
ctx.clone(),
user_id,
- request.clone(),
+ request,
toolset.toolset,
sender,
incoming_message.chat_id.as_str(),
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs
index 1ea1ee759e..ee4f7ed98a 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs
@@ -10,7 +10,7 @@ use uuid::Uuid;
use ai::{
chat_stream::get_chat_stream,
- types::{ChatCompletionRequest, ChatMessage, ChatStreamCompletionResponse, PromptAttachment},
+ types::{ChatCompletionRequest, ChatMessage, ChatStreamCompletionResponse},
};
use tokio::sync::mpsc::UnboundedSender;
@@ -28,6 +28,8 @@ use macro_db_client::dcs::{
get_document::get_document, get_document_text::get_pdf_docx_document_text,
};
+use ai_format::document::Document;
+
use super::connection::ws_send;
pub fn normalize_text(text: &str) -> String {
@@ -70,7 +72,7 @@ async fn build_completion_request(
ctx: Arc<ApiContext>,
payload: &SendCompletionPayload,
) -> Result<ChatCompletionRequest> {
- let mut prompt_attachments: Vec<PromptAttachment> = vec![];
+ let mut prompt_attachments = vec![];
if let (Some(attachment_id), Some(selected_text)) = (
payload.attachment_id.as_ref(),
@@ -94,12 +96,15 @@ async fn build_completion_request(
if let Some(context) =
find_text_context(&document_text.content, selected_text)?
{
- prompt_attachments.push(PromptAttachment {
- id: attachment_id.to_string(),
- file_type: f.as_str().to_string(),
- name: document.name,
- content: context,
- });
+ prompt_attachments.push(
+ Document {
+ id: attachment_id.to_string(),
+ file_type: f.as_str().to_string(),
+ name: document.name,
+ content: context,
+ }
+ .boxed(),
+ );
} else {
tracing::warn!(
document_id=%attachment_id,
@@ -118,12 +123,15 @@ async fn build_completion_request(
"document content is empty"
);
} else {
- prompt_attachments.push(PromptAttachment {
- id: attachment_id.to_string(),
- file_type: file_type.as_str().to_string(),
- name: document.name,
- content,
- });
+ prompt_attachments.push(
+ Document {
+ id: attachment_id.to_string(),
+ file_type: file_type.as_str().to_string(),
+ name: document.name,
+ content,
+ }
+ .boxed(),
+ );
}
}
}
diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs
index b3f3a59e53..898764e4d2 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs
@@ -1,6 +1,7 @@
use crate::api::context::DcsScribe;
use crate::core::constants::CHANNEL_TRANSCRIPT_MAX_MESSAGES;
-use ai::types::{Attachment, PromptAttachment};
+use ai::types::{Attachment, ImageData};
+use ai_format::document::Document;
use ai_tools::read::EmailMessage;
use model::{
chat::{AttachmentType, ChatAttachmentWithName},
@@ -32,23 +33,25 @@ pub async fn fetchium(
.content()
.await?
.to_string();
- Ok(Attachment::Text(PromptAttachment {
- id: attachment.attachment_id.clone(),
- file_type: "Project".into(),
- name: attachment.name().unwrap_or_default().into(),
- content: project_items,
- }))
+ Ok(Attachment::Text(
+ Document {
+ id: attachment.attachment_id.clone(),
+ file_type: "Project".into(),
+ name: attachment.name().unwrap_or_default().into(),
+ content: project_items,
+ }
+ .boxed(),
+ ))
}
AttachmentType::Image => {
- let base64_image = scribe
+ let image = scribe
.static_file
.fetch(attachment.attachment_id.clone())
.file_content()
.await?
- .content
- .base64_compressed_webp()?;
+ .content;
- Ok(Attachment::ImageUrl(base64_image))
+ Ok(Attachment::Image(ImageData::try_from(image)?))
}
AttachmentType::Channel => {
let transcript = scribe
@@ -61,12 +64,15 @@ pub async fn fetchium(
)
.await?;
- Ok(Attachment::Text(PromptAttachment {
- content: transcript,
- file_type: "channel".into(),
- id: attachment.attachment_id.clone(),
- name: "unknown channel name".into(),
- }))
+ Ok(Attachment::Text(
+ Document {
+ content: transcript,
+ file_type: "channel".into(),
+ id: attachment.attachment_id.clone(),
+ name: "unknown channel name".into(),
+ }
+ .boxed(),
+ ))
}
AttachmentType::Document => {
let document = scribe
@@ -75,16 +81,17 @@ pub async fn fetchium(
.document_content()
.await?;
if document.file_type().is_image() {
- Ok(Attachment::ImageUrl(
- document.content.base64_compressed_webp()?,
- ))
+ Ok(Attachment::Image(ImageData::try_from(document.content)?))
} else {
- Ok(Attachment::Text(PromptAttachment {
- id: attachment.attachment_id,
- name: document.metadata().document_name.clone(),
- file_type: document.file_type().to_string(),
- content: document.content.text_content()?,
- }))
+ Ok(Attachment::Text(
+ Document {
+ id: attachment.attachment_id,
+ name: document.metadata().document_name.clone(),
+ file_type: document.file_type().to_string(),
+ content: document.content.text_content()?,
+ }
+ .boxed(),
+ ))
}
}
AttachmentType::Email => {
@@ -117,12 +124,15 @@ pub async fn fetchium(
let content = serde_json::to_string_pretty(&formatted_content)?;
- Ok(Attachment::Text(PromptAttachment {
- id: attachment.attachment_id,
- name: subject.clone(),
- file_type: "email".to_string(),
- content,
- }))
+ Ok(Attachment::Text(
+ Document {
+ id: attachment.attachment_id,
+ name: subject.clone(),
+ file_type: "email".to_string(),
+ content,
+ }
+ .boxed(),
+ ))
}
}
}
diff --git a/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs b/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs
index d2d8d6b504..680a541545 100644
--- a/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs
+++ b/rust/cloud-storage/insight_service/src/insight/consumer/generator.rs
@@ -8,7 +8,7 @@ use crate::insight::consumer::{INSIGHT_MODEL, Insights};
use crate::insight::deduplication::{DeduplicationConfig, InsightDeduplicator};
use ai::structured_output_v2::structured_completion_v2;
use ai::types::{MessageBuilder, RequestBuilder};
-use ai_format::InsightContextLog;
+use ai_format::insight_context_log::InsightContextLog;
use anyhow::{Context, Result};
use model::insight_context::UserInsightRecord;
use std::fmt::Display;
diff --git a/rust/cloud-storage/model/src/insight_context/chat.rs b/rust/cloud-storage/model/src/insight_context/chat.rs
index 60d27bdfda..3a85a409bf 100644
--- a/rust/cloud-storage/model/src/insight_context/chat.rs
+++ b/rust/cloud-storage/model/src/insight_context/chat.rs
@@ -1,4 +1,5 @@
-use ai_format::{Indent, InsightContextLog, Truncate, format_date};
+use ai_format::insight_context_log::InsightContextLog;
+use ai_format::util::{Indent, Truncate, format_date};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone)]
diff --git a/rust/cloud-storage/model/src/insight_context/mod.rs b/rust/cloud-storage/model/src/insight_context/mod.rs
index b910e7edfa..8e275d0b6d 100644
--- a/rust/cloud-storage/model/src/insight_context/mod.rs
+++ b/rust/cloud-storage/model/src/insight_context/mod.rs
@@ -3,7 +3,7 @@ pub mod document;
pub mod email_insights;
pub mod insights_backfill;
-use ai_format::format_date;
+use ai_format::util::format_date;
use chrono::serde::{ts_seconds, ts_seconds_option};
use chrono::{DateTime, Utc};
use email_insights::{EmailInfo, GenerateEmailInsightContext};
diff --git a/rust/cloud-storage/scribe/Cargo.toml b/rust/cloud-storage/scribe/Cargo.toml
index 0c29e3e138..486dfbc01d 100644
--- a/rust/cloud-storage/scribe/Cargo.toml
+++ b/rust/cloud-storage/scribe/Cargo.toml
@@ -53,9 +53,7 @@ sync_service_client = { path = "../sync_service_client", optional = true }
comms_service_client = { path = "../comms_service_client", optional = true }
document_cognition_service_client = { path = "../document_cognition_service_client", optional = true }
email_service_client = { path = "../email_service_client", optional = true }
-image = "0.25.9"
models_comms = { path = "../models_comms", optional = true }
models_email = { path = "../models_email", optional = true }
models_sfs = { path = "../models_sfs", optional = true }
static_file_service_client = { path = "../static_file_service_client", optional = true }
-webp = "0.3.1"
diff --git a/rust/cloud-storage/scribe/src/channel/client.rs b/rust/cloud-storage/scribe/src/channel/client.rs
index 6d46bd7224..4ea8dd5639 100644
--- a/rust/cloud-storage/scribe/src/channel/client.rs
+++ b/rust/cloud-storage/scribe/src/channel/client.rs
@@ -1,4 +1,5 @@
-use ai_format::{Indent, InsightContextLog};
+use ai_format::insight_context_log::InsightContextLog;
+use ai_format::util::Indent;
use anyhow::Error;
use comms_service_client::CommsServiceClient;
use models_comms::channel::ChannelMetadata;
diff --git a/rust/cloud-storage/scribe/src/compress_image.rs b/rust/cloud-storage/scribe/src/compress_image.rs
deleted file mode 100644
index 5b4d4a1656..0000000000
--- a/rust/cloud-storage/scribe/src/compress_image.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use anyhow::Result;
-use base64::Engine;
-use base64::engine::general_purpose;
-use image::{DynamicImage, GenericImageView};
-use webp::Encoder;
-
-const ENCODING_QUALITY: f32 = 75.0;
-const MAX_SIZE_W: u32 = 1080;
-const MAX_SIZE_H: u32 = 720;
-
-pub fn make_compressed_base64_webp(image_bytes: &[u8]) -> Result<String> {
- let img = image::load_from_memory(image_bytes)?;
- let resized_img = resize_if_needed(img);
- let rgb_img = resized_img.to_rgb8();
- let encoder = Encoder::from_rgb(&rgb_img, rgb_img.width(), rgb_img.height());
- let webp_data = encoder.encode(ENCODING_QUALITY);
- let base64_string = general_purpose::STANDARD.encode(&*webp_data);
- Ok(format!("data:image/webp;base64,{}", base64_string))
-}
-
-fn resize_if_needed(img: DynamicImage) -> DynamicImage {
- let (width, height) = img.dimensions();
-
- // Check if resize is needed
- if width <= MAX_SIZE_W && height <= MAX_SIZE_H {
- return img;
- }
-
- // Calculate new dimensions while maintaining aspect ratio
- let width_ratio = MAX_SIZE_W as f32 / width as f32;
- let height_ratio = MAX_SIZE_H as f32 / height as f32;
- let ratio = width_ratio.min(height_ratio);
-
- let new_width = (width as f32 * ratio) as u32;
- let new_height = (height as f32 * ratio) as u32;
-
- img.resize(new_width, new_height, image::imageops::FilterType::Lanczos3)
-}
diff --git a/rust/cloud-storage/scribe/src/document/types.rs b/rust/cloud-storage/scribe/src/document/types.rs
index 02ea1e1d81..db8c729dcc 100644
--- a/rust/cloud-storage/scribe/src/document/types.rs
+++ b/rust/cloud-storage/scribe/src/document/types.rs
@@ -1,5 +1,5 @@
-use crate::compress_image::make_compressed_base64_webp;
-use anyhow::Error;
+use ai::types::ImageData;
+use anyhow::{Error, bail};
use bytes::Bytes;
use lexical_client::types::CognitionResponseData;
use model::document::response::LocationResponseV3;
@@ -20,6 +20,19 @@ pub enum Data {
Markdown(CognitionResponseData),
}
+impl TryFrom<DocumentContent> for ImageData {
+ type Error = anyhow::Error;
+ fn try_from(value: DocumentContent) -> Result<Self, Self::Error> {
+ if value.file_type.is_image()
+ && let Data::Binary(bytes) = value.data
+ {
+ ImageData::try_from_bytes(bytes.into())
+ } else {
+ bail!("No conversion to image")
+ }
+ }
+}
+
impl std::fmt::Debug for Data {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
@@ -42,18 +55,7 @@ impl DocumentContent {
if self.file_type.is_text_content() {
Ok(self.data.to_string())
} else {
- Err(anyhow::anyhow!("Document is not text"))
- }
- }
-
- #[tracing::instrument(err)]
- pub fn base64_compressed_webp(self) -> Result<String, Error> {
- if self.file_type.is_image()
- && let Some(bytes) = self.data.binary_data()
- {
- make_compressed_base64_webp(&bytes)
- } else {
- Err(anyhow::anyhow!("Data is not in image format"))
+ bail!("Document is not text")
}
}
}
diff --git a/rust/cloud-storage/scribe/src/lib.rs b/rust/cloud-storage/scribe/src/lib.rs
index 6715c25187..6d19bd685b 100644
--- a/rust/cloud-storage/scribe/src/lib.rs
+++ b/rust/cloud-storage/scribe/src/lib.rs
@@ -1,7 +1,6 @@
#[cfg(feature = "channel")]
pub mod channel;
-mod compress_image;
#[cfg(feature = "dcs")]
pub mod dcs;
#[cfg(feature = "document")]
diff --git a/rust/cloud-storage/scribe/src/static_file/types.rs b/rust/cloud-storage/scribe/src/static_file/types.rs
index 612f94d00f..55277c3654 100644
--- a/rust/cloud-storage/scribe/src/static_file/types.rs
+++ b/rust/cloud-storage/scribe/src/static_file/types.rs
@@ -1,5 +1,5 @@
-use crate::compress_image::make_compressed_base64_webp;
-use anyhow::Error;
+use ai::types::ImageData;
+use anyhow::{Error, bail};
use model::document::{ContentType, ContentTypeExt};
use models_sfs::FileMetadata;
@@ -14,6 +14,19 @@ pub struct StaticFileContent {
pub metadata: FileMetadata,
}
+impl TryFrom<StaticFileContent> for ImageData {
+ type Error = anyhow::Error;
+ fn try_from(value: StaticFileContent) -> Result<Self, Self::Error> {
+ if value.content_type.is_image()
+ && let Data::Binary(bytes) = value.data
+ {
+ ImageData::try_from_bytes(bytes.into())
+ } else {
+ bail!("No conversion to image")
+ }
+ }
+}
+
impl StaticFileContent {
pub fn metadata(&self) -> &FileMetadata {
&self.metadata
@@ -25,18 +38,7 @@ impl StaticFileContent {
if self.content_type.is_text_content() {
Ok(self.data.to_string())
} else {
- Err(anyhow::anyhow!("Static file is not text"))
- }
- }
-
- #[tracing::instrument(err)]
- pub fn base64_compressed_webp(self) -> Result<String, Error> {
- if self.content_type.is_image()
- && let Some(bytes) = self.data.binary_data()
- {
- make_compressed_base64_webp(&bytes)
- } else {
- Err(anyhow::anyhow!("Data is not in image format"))
+ bail!("Static file is not text")
}
}
}