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.

fix images for the anthropic crate (#62)

Eric Hayes99f0543a4225
diff --git a/rust/cloud-storage/.gitignore b/rust/cloud-storage/.gitignore
index f44d108349..a8bac09d6f 100644
--- a/rust/cloud-storage/.gitignore
+++ b/rust/cloud-storage/.gitignore
@@ -9,6 +9,7 @@
!/target/lambda/**/bootstrap.zip
!*/**/.env.sample
+*/**/.env
# Jetbrains IDE files
-**/.idea/
\ No newline at end of file
+**/.idea/
diff --git a/rust/cloud-storage/ai/src/types/request_builder.rs b/rust/cloud-storage/ai/src/types/request_builder.rs
index dc0319e3d6..567b0a244a 100644
--- a/rust/cloud-storage/ai/src/types/request_builder.rs
+++ b/rust/cloud-storage/ai/src/types/request_builder.rs
@@ -90,7 +90,7 @@ impl RequestBuilder<Model, Vec<ChatMessage>, String> {
.collect::<(Vec<_>, Vec<_>)>();
let image_attachments = image_attachments.into_iter().flatten().collect::<Vec<_>>();
- let prompt_attachments = prompt_attachments.into_iter().flatten().collect();
+ 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),
diff --git a/rust/cloud-storage/anthropic/src/client/mod.rs b/rust/cloud-storage/anthropic/src/client/mod.rs
index 7778612aa5..5633fbf65c 100644
--- a/rust/cloud-storage/anthropic/src/client/mod.rs
+++ b/rust/cloud-storage/anthropic/src/client/mod.rs
@@ -47,9 +47,10 @@ impl Client {
request: I,
) -> Pin<Box<dyn Stream<Item = Result<O, AnthropicError>> + Send>>
where
- I: Serialize,
+ I: Serialize + std::fmt::Debug,
O: DeserializeOwned + Send + Sync + 'static,
{
+ tracing::debug!("{:#?}", request);
let event_source = self
.http_client
.post(format!("{}{}", self.config.api_base, path))
diff --git a/rust/cloud-storage/anthropic/src/openai/request/conversions.rs b/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
index 010032daed..cc3560de35 100644
--- a/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
+++ b/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
@@ -1,4 +1,7 @@
-use crate::types::request::{self, SystemPrompt};
+use crate::{
+ prelude::ImageSource,
+ types::request::{self, SystemPrompt},
+};
use async_openai::types::{
ChatCompletionRequestAssistantMessage, ChatCompletionRequestDeveloperMessage,
ChatCompletionRequestFunctionMessage, ChatCompletionRequestMessage,
@@ -205,11 +208,9 @@ impl From<ChatCompletionRequestUserMessage> for request::RequestMessage {
.filter_map(|part| {
match part {
async_openai::types::ChatCompletionRequestUserMessageContentPart::ImageUrl(url) => {
- Some(if is_url(&url.image_url.url) {
- request::RequestContentKind::Url { url: url.image_url.url }
- } else {
- let kind = media_type(&url.image_url.url);
- request::RequestContentKind::Base64 { data: url.image_url.url, media_type: kind }
+ Some(request::RequestContentKind::Image {
+ cache_control: None,
+ source: url_to_image_source(url.image_url.url)
})
},
async_openai::types::ChatCompletionRequestUserMessageContentPart::Text(text) =>
@@ -333,6 +334,25 @@ impl From<ChatCompletionTool> for request::Tool {
}
}
+fn url_to_image_source(url: String) -> ImageSource {
+ if is_url(&url) {
+ ImageSource::Url { url }
+ } else {
+ let kind = media_type(&url);
+ if let Some(data) = url.split("base64,").take(2).collect::<Vec<_>>().get(1) {
+ ImageSource::Base64 {
+ data: data.to_string(),
+ media_type: kind,
+ }
+ } else {
+ ImageSource::Base64 {
+ data: url.to_owned(),
+ media_type: kind,
+ }
+ }
+ }
+}
+
fn system_message_as_text_pars(sys_msg: &ChatCompletionRequestSystemMessage) -> Vec<&str> {
match sys_msg.content {
async_openai::types::ChatCompletionRequestSystemMessageContent::Array(ref parts) => parts
diff --git a/rust/cloud-storage/anthropic/src/openai/stream_response.rs b/rust/cloud-storage/anthropic/src/openai/stream_response.rs
index 7a846069e8..6bf3e523f9 100644
--- a/rust/cloud-storage/anthropic/src/openai/stream_response.rs
+++ b/rust/cloud-storage/anthropic/src/openai/stream_response.rs
@@ -287,7 +287,7 @@ impl<'c> Chat<'c> {
request: I,
) -> ChatCompletionResponseStream
where
- I: Serialize,
+ I: Serialize + std::fmt::Debug,
{
map_stream(self.inner.post_stream("/v1/messages", request).await)
}
diff --git a/rust/cloud-storage/anthropic/src/types/request.rs b/rust/cloud-storage/anthropic/src/types/request.rs
index 57a0bc4afc..6dbcc179bb 100644
--- a/rust/cloud-storage/anthropic/src/types/request.rs
+++ b/rust/cloud-storage/anthropic/src/types/request.rs
@@ -23,13 +23,10 @@ pub enum RequestContentKind {
// TODO?
citations: Vec<serde_json::Value>,
},
- Base64 {
- data: String,
- /// one of image/jpeg | image/png | image/gif | image/webp
- media_type: String,
- },
- Url {
- url: String,
+ Image {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cache_control: Option<CacheControl>,
+ source: ImageSource,
},
ToolUse {
id: String,
@@ -48,6 +45,21 @@ pub enum RequestContentKind {
},
}
+// https://docs.claude.com/en/api/messages#image
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ImageSource {
+ #[serde(rename = "base64")]
+ Base64 {
+ data: String,
+ media_type: String,
+ },
+
+ Url {
+ url: String,
+ },
+}
+
// who cares https://docs.claude.com/en/api/messages#tool-result
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct CacheControl(serde_json::Value);
diff --git a/rust/cloud-storage/document_cognition_service/justfile b/rust/cloud-storage/document_cognition_service/justfile
index 1237dc28ac..a982ed62a1 100644
--- a/rust/cloud-storage/document_cognition_service/justfile
+++ b/rust/cloud-storage/document_cognition_service/justfile
@@ -19,7 +19,7 @@ run:
cargo run --features macro_middleware/local_auth
debug:
- RUST_LOG=document_cognition_service=debug,ai=debug,ai_tools=debug,info cargo run --features macro_middleware/local_auth
+ RUST_LOG=document_cognition_service=debug,ai=debug,ai_tools=debug,anthropic=debug,info cargo run --features macro_middleware/local_auth
trace:
RUST_LOG=document_cognition_service=trace,ai=trace,ai_tools=debug,anthropic=debug,info, cargo run --features macro_middleware/local_auth
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/attachment.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/attachment.rs
deleted file mode 100644
index c3609f887d..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/attachment.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-use crate::api::context::ApiContext;
-use crate::core::constants::CHANNEL_TRANSCRIPT_MAX_MESSAGES;
-use crate::service::attachment::document::get_document_plaintext_content;
-use ai::types::PromptAttachment;
-use anyhow::{Context, Error};
-use futures::FutureExt;
-use futures::future::try_join_all;
-use model::chat::{AttachmentMetadata, ChatAttachmentWithName};
-use std::sync::Arc;
-
-#[tracing::instrument(err, skip_all, fields(attachment_count = attachments.len()))]
-pub async fn get_prompt_attachments(
- ctx: Arc<ApiContext>,
- attachments: Vec<ChatAttachmentWithName>,
-) -> Result<Vec<PromptAttachment>, Error> {
- #[expect(clippy::type_complexity, reason = "too annoying to fix now")]
- let mut requests: Vec<
- std::pin::Pin<Box<dyn futures::Future<Output = Result<PromptAttachment, Error>> + Send>>,
- > = Vec::new();
-
- for att in attachments.into_iter() {
- let ctx = ctx.clone();
- match att.metadata {
- Some(AttachmentMetadata::Document { document_type, .. })
- if document_type.is_text_content() =>
- {
- let attachment_id = att.attachment_id;
- let file_type = document_type.to_string();
- let document_id = attachment_id.clone();
- let document_request = async move {
- let document_metadata = get_document_plaintext_content(&ctx, &attachment_id)
- .await
- .context("failed to get document plaintext content")?;
- Ok(PromptAttachment {
- id: document_id,
- file_type,
- name: document_metadata.metadata().document_name.clone(),
- content: document_metadata
- .text_content()
- .context("failed to extract text content from document")?,
- })
- };
- requests.push(document_request.boxed());
- }
- Some(AttachmentMetadata::Channel {
- channel_name,
- channel_type: _,
- }) => {
- let id = att.attachment_id;
- let channel_request = async move {
- let since = None; // no time limit
- let limit = Some(CHANNEL_TRANSCRIPT_MAX_MESSAGES);
- let content = ctx
- .scribe
- .channel
- .get_channel_transcript(id.as_str(), None, since, limit)
- .await
- .map_err(|e| {
- tracing::error!(channel_id = %id, error = %e, "failed to get channel transcript");
- anyhow::anyhow!("failed to get channel transcript")
- })?;
- Ok(PromptAttachment {
- id,
- file_type: "channel".to_string(),
- name: channel_name,
- content,
- })
- };
- requests.push(channel_request.boxed());
- }
- _ => {}
- }
- }
-
- Ok(try_join_all(requests)
- .await
- .context("failed to fetch attachment content")?
- .into_iter()
- .collect())
-}
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 21d3e28254..12c2de3cfc 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
@@ -1,5 +1,4 @@
mod ai_request;
-mod attachment;
mod toolset;
use crate::api::ws::connection::{