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.

feat(tools): context extraction (#1016)

Eric Hayesdb286dfadba8
diff --git a/rust/cloud-storage/CLAUDE.md b/rust/cloud-storage/CLAUDE.md
index 992c065a65..b0a071f2f5 100644
--- a/rust/cloud-storage/CLAUDE.md
+++ b/rust/cloud-storage/CLAUDE.md
@@ -258,6 +258,8 @@ The migration included comprehensive indexes:
- Add `#![deny(missing_docs)]` to `lib.rs` in new crates to enforce documentation on all public items
- This ensures all public functions, structs, enums, and modules have documentation comments
+- Do not use `ignore` to except code blocks from doc tests unless explicitely directed
+
### Test File Organization
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a306ff47d6..05ea93bb62 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -92,6 +92,7 @@ dependencies = [
"anthropic",
"anyhow",
"async-trait",
+ "axum",
"chrono",
"comms_service_client",
"cool_asserts",
@@ -124,7 +125,10 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
+ "axum",
+ "axum-macros",
"futures",
+ "macro_user_id",
"schemars",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs b/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
index 953bb87d49..db32481912 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
@@ -6,23 +6,21 @@ use crate::types::ExtendedClient;
use anthropic::openai::request::{AnthropicRequestExtension, AnthropicRequestExtensions};
use std::sync::Arc;
-pub struct ToolLoop<I, T, R>
+pub struct ToolLoop<I, T>
where
I: ExtendedClient + Clone + Send + Sync,
T: Clone + Send + Sync,
- R: Clone + Send + Sync,
{
client: I,
context: T,
- toolset: Arc<AsyncToolSet<T, R>>,
+ toolset: Arc<AsyncToolSet<T>>,
}
-impl<T, R> ToolLoop<AnthropicClient, T, R>
+impl<T> ToolLoop<AnthropicClient, T>
where
T: Clone + Send + Sync,
- R: Clone + Send + Sync,
{
- pub fn new(toolset: AsyncToolSet<T, R>, context: T) -> Self {
+ pub fn new(toolset: AsyncToolSet<T>, context: T) -> Self {
let extensions = AnthropicRequestExtensions(vec![
AnthropicRequestExtension::WebSearchTool,
AnthropicRequestExtension::FetchTool,
@@ -37,13 +35,12 @@ where
}
}
-impl<I, T, R> ToolLoop<I, T, R>
+impl<I, T> ToolLoop<I, T>
where
I: ExtendedClient + Clone + Send + Sync,
T: Clone + Send + Sync,
- R: Clone + Send + Sync,
{
- pub fn chat(&self) -> Chat<I, T, R> {
+ pub fn chat(&self) -> Chat<I, T> {
Chat::new(
self.client.clone(),
self.toolset.clone(),
@@ -51,7 +48,7 @@ where
)
}
- pub fn chained(&self) -> Chained<I, T, R> {
+ pub fn chained(&self) -> Chained<I, T> {
Chained::new(
self.client.clone(),
self.toolset.clone(),
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 3aff2a7a34..81d6ab16d0 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs
@@ -1,7 +1,9 @@
use crate::generate_tool_input_schema;
use crate::tool::completion::tool_completion;
use crate::tool::tool_loop::constant::{MAX_RECURSIONS, TOOL_GENERATOR};
-use crate::tool::types::{AsyncToolSet, PartialToolCall, StreamPart, ToolCall, ToolResult};
+use crate::tool::types::{
+ AsyncToolSet, PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult,
+};
use crate::tool::types::{ChatCompletionStream, ToolResponse};
use crate::types::openai::message::convert_message;
@@ -68,7 +70,7 @@ impl ChainedTool {
}
}
-fn build_tool_prompt<T, R>(toolset: &AsyncToolSet<T, R>) -> String {
+fn build_tool_prompt<T>(toolset: &AsyncToolSet<T>) -> String {
toolset
.tools
.values()
@@ -85,14 +87,13 @@ description: {}
.join("\n")
}
-pub struct Chained<I, T, R>
+pub struct Chained<I, T>
where
I: ExtendedClient + Send + Sync + Clone,
T: Clone + Send + Sync + 'static,
- R: Send + Sync + 'static,
{
inner: I,
- toolset: Arc<AsyncToolSet<T, R>>,
+ toolset: Arc<AsyncToolSet<T>>,
request: CreateChatCompletionRequest,
messages: Vec<ChatCompletionRequestMessage>,
context: T,
@@ -101,13 +102,12 @@ where
tool_call_count: usize,
}
-impl<I, T, R> Chained<I, T, R>
+impl<I, T> Chained<I, T>
where
I: ExtendedClient + Send + Sync + Clone,
T: Clone + Send + Sync,
- R: Clone + Send + Sync,
{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T, R>>, context: T) -> Chained<I, T, R> {
+ pub fn new(client: I, toolset: Arc<AsyncToolSet<T>>, context: T) -> Chained<I, T> {
Self {
inner: client,
toolset,
@@ -123,7 +123,7 @@ where
pub async fn send_message(
&mut self,
mut request: ChatCompletionRequest,
- request_context: R,
+ request_context: RequestContext,
) -> Result<ChatCompletionStream<'_>> {
// tell the primary model how all the tools will work
request
@@ -150,7 +150,7 @@ where
}
async fn route_chained_calls(
- toolset: &Arc<AsyncToolSet<T, R>>,
+ toolset: &Arc<AsyncToolSet<T>>,
part: ToolCall,
) -> Result<ToolCall> {
tracing::debug!("route chained call {:#?}", part);
@@ -186,7 +186,7 @@ where
async fn make_chat_completion_stream(
&mut self,
- request_context: R,
+ request_context: RequestContext,
) -> Result<ChatCompletionStream<'_>> {
let item_stream = stream!({
let mut stream_parts = vec![];
@@ -244,7 +244,7 @@ where
async fn process_stream_parts(
&mut self,
stream_parts: Vec<StreamPart>,
- request_context: R,
+ request_context: RequestContext,
) -> ProcessedStream {
// list of all tool calls
let mut tool_calls = vec![];
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
index 2a34d4542a..8c5d39135f 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
@@ -1,6 +1,8 @@
use super::constant::MAX_RECURSIONS;
use crate::openai_toolset::OpenAIToolSetExt;
-use crate::tool::types::{AsyncToolSet, PartialToolCall, StreamPart, ToolCall, ToolResult};
+use crate::tool::types::{
+ AsyncToolSet, PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult,
+};
use crate::tool::types::{ChatCompletionStream, ExtendedPartStream, PartOrExt, ToolResponse};
use crate::types::openai::message::convert_message;
use crate::types::traits::{ExtendedOpenAIStream, ExtendedOpenAIStreamItem};
@@ -22,14 +24,13 @@ struct ProcessedStream {
pub tool_responses: Vec<ToolResponse>,
}
-pub struct Chat<I, T, R>
+pub struct Chat<I, T>
where
I: ExtendedClient + Send + Sync,
T: Clone + Send + Sync + 'static,
- R: Send + Sync + 'static,
{
client: I,
- toolset: Arc<AsyncToolSet<T, R>>,
+ toolset: Arc<AsyncToolSet<T>>,
request: CreateChatCompletionRequest,
messages: Vec<ChatCompletionRequestMessage>,
context: T,
@@ -38,13 +39,12 @@ where
user_id: String,
}
-impl<I, T, R> Chat<I, T, R>
+impl<I, T> Chat<I, T>
where
I: ExtendedClient + Send + Sync,
T: Clone + Send + Sync,
- R: Clone + Send + Sync,
{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T, R>>, context: T) -> Chat<I, T, R> {
+ pub fn new(client: I, toolset: Arc<AsyncToolSet<T>>, context: T) -> Chat<I, T> {
Chat {
client,
toolset,
@@ -60,7 +60,7 @@ where
pub async fn send_message(
&mut self,
request: ChatCompletionRequest,
- request_context: R,
+ request_context: RequestContext,
user_id: String,
) -> Result<ChatCompletionStream<'_>> {
self.request = request.try_into()?;
@@ -84,7 +84,7 @@ where
async fn make_chat_completion_stream(
&mut self,
- request_context: R,
+ request_context: RequestContext,
) -> Result<ChatCompletionStream<'_>> {
let item_stream = stream!({
let mut stream_parts = vec![];
@@ -144,7 +144,7 @@ where
async fn process_stream_parts(
&mut self,
stream_parts: Vec<PartOrExt<I::ResponseExtension>>,
- request_context: R,
+ request_context: RequestContext,
) -> ProcessedStream {
let mut messages: Vec<ChatCompletionRequestMessage> = vec![];
let mut tool_stream_parts: Vec<ToolResponse> = vec![];
@@ -405,7 +405,7 @@ mod tests {
};
use serde_json::json;
- fn create_mock_chat() -> Chat<NoOpClient, String, String> {
+ fn create_mock_chat() -> Chat<NoOpClient, String> {
let client = NoOpClient;
let toolset = Arc::new(AsyncToolSet::new());
Chat::new(client, toolset, "test_context".to_string())
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index ad71718488..00ecb245c1 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -9,6 +9,7 @@ ai = { path = "../ai" }
ai_toolset = { path = "../ai_toolset" }
anyhow.workspace = true
async-trait.workspace = true
+axum = { workspace = true, features = ["macros"] }
chrono.workspace = true
comms_service_client = { path = "../comms_service_client" }
email = { path = "../email", features = ["ai_schema", "axum"] }
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 9b0266da0e..951ce41adf 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -8,6 +8,7 @@ pub mod search;
mod tool_context;
pub mod web_fetch;
use search::web::anthropic_web_search::anthropic_web_search_tool;
+use std::sync::Arc;
use web_fetch::anthropic_web_fetch_tool;
pub use search::search_toolset;
@@ -15,7 +16,7 @@ pub use tool_context::*;
use crate::list::list_toolset;
-pub type AiToolSet = AsyncToolSet<ToolServiceContext, RequestContext>;
+pub type AiToolSet = AsyncToolSet<ToolServiceContext>;
pub struct ToolSetWithPrompt {
pub toolset: AiToolSet,
@@ -35,9 +36,9 @@ pub fn all_tools() -> ToolSetWithPrompt {
.expect("failed to add search toolset")
.add_toolset(list_toolset())
.expect("failed to add list toolset")
- .add_tool::<read::Read>()
+ .add_tool::<read::Read, Arc<ToolScribe>>()
.expect("read tool")
- .add_tool::<rewrite::MarkdownRewrite>()
+ .add_tool::<rewrite::MarkdownRewrite, Arc<ToolScribe>>()
.expect("markdown revision tool");
let prompt = prompts::TOOLS_PROMPT;
ToolSetWithPrompt { toolset, prompt }
diff --git a/rust/cloud-storage/ai_tools/src/list/channel/tool.rs b/rust/cloud-storage/ai_tools/src/list/channel/tool.rs
index 4c337d3908..c4e8ca6d07 100644
--- a/rust/cloud-storage/ai_tools/src/list/channel/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/list/channel/tool.rs
@@ -1,9 +1,10 @@
-use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use crate::tool_context::ToolScribe;
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use model::comms::ChannelType;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use std::sync::Arc;
use uuid::Uuid;
/// A channel item returned by the list channels tool
@@ -41,21 +42,21 @@ pub struct ListChannels {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for ListChannels {
+impl AsyncTool<Arc<ToolScribe>> for ListChannels {
type Output = ListChannelsResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[allow(deprecated)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- context: ToolServiceContext,
+ scribe: ServiceContext<Arc<ToolScribe>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!("List channels");
- let channels = context
- .scribe
+ let channels = scribe
.channel
- .list_channels(&request_context.jwt_token)
+ .list_channels(&request_context.jwt)
.await
.map_err(|e| ToolCallError {
description: format!("failed to list channels: {}", e),
diff --git a/rust/cloud-storage/ai_tools/src/list/email/tool.rs b/rust/cloud-storage/ai_tools/src/list/email/tool.rs
index c4373e5f9e..ffe938774e 100644
--- a/rust/cloud-storage/ai_tools/src/list/email/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/list/email/tool.rs
@@ -1,13 +1,14 @@
-use crate::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use email::inbound::ApiPaginatedThreadCursor;
+use email_service_client::EmailServiceClientExternal;
use models_email::{
email::service::thread::PreviewView, service::thread::PreviewViewStandardLabel,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
+use std::sync::Arc;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "camelCase")]
@@ -93,13 +94,14 @@ impl ListEmails {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for ListEmails {
+impl AsyncTool<Arc<EmailServiceClientExternal>> for ListEmails {
type Output = ApiPaginatedThreadCursor;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[allow(deprecated)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- service_context: ToolServiceContext,
+ email_client: ServiceContext<Arc<EmailServiceClientExternal>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(self=?self, "List emails params");
@@ -118,9 +120,8 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ListEmails {
.map(|label| PreviewView::UserLabel(label.clone())))
.unwrap_or(default_view());
- service_context
- .email_service_client
- .get_thread_previews_external(self.iter_params(), view, &request_context.jwt_token)
+ email_client
+ .get_thread_previews_external(self.iter_params(), view, &request_context.jwt)
.await
.map_err(|err| ToolCallError {
description: format!("something went wrong fetching emails {:?}", err),
diff --git a/rust/cloud-storage/ai_tools/src/list/file.rs b/rust/cloud-storage/ai_tools/src/list/file.rs
index 0bb171a608..610c1c3ac6 100644
--- a/rust/cloud-storage/ai_tools/src/list/file.rs
+++ b/rust/cloud-storage/ai_tools/src/list/file.rs
@@ -1,11 +1,12 @@
-use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use crate::tool_context::ToolScribe;
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use model::document::list::DocumentListItem;
use models_permissions::share_permission::access_level::AccessLevel;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::cmp::min;
+use std::sync::Arc;
/// Maximum number of results to return to the AI client
const TRUNCATED_RESULTS_LIMIT: usize = 150;
@@ -109,7 +110,7 @@ impl ListDocuments {
async fn fetch_all_pages(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
min_access_level: AccessLevel,
page_size: i64,
@@ -119,12 +120,11 @@ impl ListDocuments {
loop {
let page = page_offset / page_size;
- let response = context
- .scribe
+ let response = scribe
.document
.dss_client
.list_documents_with_access(
- &request_context.user_id,
+ (*request_context.user_id).as_ref(),
self.file_types.clone(),
Some(min_access_level),
page,
@@ -158,13 +158,13 @@ impl ListDocuments {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for ListDocuments {
+impl AsyncTool<Arc<ToolScribe>> for ListDocuments {
type Output = ListDocumentsResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- context: ToolServiceContext,
+ scribe: ServiceContext<Arc<ToolScribe>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(self=?self, "List documents params");
@@ -175,7 +175,7 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ListDocuments {
if self.exhaustive_search {
// Use exhaustive search to get all results
return match self
- .fetch_all_pages(&context, &request_context, min_access_level, page_size)
+ .fetch_all_pages(&scribe, &request_context, min_access_level, page_size)
.await
{
Ok(all_results) => {
@@ -204,12 +204,11 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ListDocuments {
// Non-exhaustive search - single page
let page = page_offset / page_size;
- match context
- .scribe
+ match scribe
.document
.dss_client
.list_documents_with_access(
- &request_context.user_id,
+ (*request_context.user_id).as_ref(),
self.file_types.clone(),
Some(min_access_level),
page,
diff --git a/rust/cloud-storage/ai_tools/src/list/mod.rs b/rust/cloud-storage/ai_tools/src/list/mod.rs
index e9904c895a..0d2619fe53 100644
--- a/rust/cloud-storage/ai_tools/src/list/mod.rs
+++ b/rust/cloud-storage/ai_tools/src/list/mod.rs
@@ -6,10 +6,10 @@ mod file;
pub fn list_toolset() -> AiToolSet {
AsyncToolSet::new()
- .add_tool::<channel::ListChannels>()
+ .add_tool::<channel::ListChannels, _>()
.expect("failed to add list channels")
- .add_tool::<email::ListEmails>()
+ .add_tool::<email::ListEmails, _>()
.expect("failed to add list email")
- .add_tool::<file::ListDocuments>()
+ .add_tool::<file::ListDocuments, _>()
.expect("failed to add list documents")
}
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
index 8cb73b3db8..3acad3cc8a 100644
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ b/rust/cloud-storage/ai_tools/src/read.rs
@@ -1,5 +1,5 @@
-use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use crate::tool_context::ToolScribe;
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use anyhow::anyhow;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -7,6 +7,7 @@ use model::chat::ChatHistory;
use models_email::email::service::message::ParsedMessage;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use std::sync::Arc;
pub const MAX_MESSAGES: i64 = 300;
@@ -132,13 +133,13 @@ pub enum ContentType {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for Read {
+impl AsyncTool<Arc<ToolScribe>> for Read {
type Output = ReadResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- context: ToolServiceContext,
+ scribe: ServiceContext<Arc<ToolScribe>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(self=?self, "Read tool params");
@@ -151,19 +152,16 @@ impl AsyncTool<ToolServiceContext, RequestContext> for Read {
}
let content = match self.content_type {
- ContentType::Document => self.read_document(&context, &request_context).await?,
- ContentType::Channel => self.read_channel(&context, &request_context).await?,
+ ContentType::Document => self.read_document(&scribe, &request_context).await?,
+ ContentType::Channel => self.read_channel(&scribe, &request_context).await?,
ContentType::ChannelMessage => {
- self.read_channel_message(&context, &request_context)
- .await?
+ self.read_channel_message(&scribe, &request_context).await?
}
- ContentType::ChatThread => self.read_chat_thread(&context, &request_context).await?,
- ContentType::ChatMessage => self.read_chat_messages(&context, &request_context).await?,
- ContentType::EmailThread => self.read_email_thread(&context, &request_context).await?,
- ContentType::EmailMessage => {
- self.read_email_message(&context, &request_context).await?
- }
- ContentType::Project => self.read_project(&context, &request_context).await?,
+ ContentType::ChatThread => self.read_chat_thread(&scribe, &request_context).await?,
+ ContentType::ChatMessage => self.read_chat_messages(&scribe, &request_context).await?,
+ ContentType::EmailThread => self.read_email_thread(&scribe, &request_context).await?,
+ ContentType::EmailMessage => self.read_email_message(&scribe, &request_context).await?,
+ ContentType::Project => self.read_project(&scribe, &request_context).await?,
};
let tool_response = ReadResponse { content };
@@ -188,9 +186,10 @@ impl Read {
Ok(self.ids[0].clone())
}
+ #[allow(deprecated)]
async fn read_project(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let id = self.ids.first().ok_or(ToolCallError {
@@ -198,10 +197,9 @@ impl Read {
internal_error: anyhow!("Bad tool args"),
})?;
- context
- .scribe
+ scribe
.document
- .fetch_project(id.to_owned(), request_context.jwt_token.clone())
+ .fetch_project(id.to_owned(), (*request_context.jwt).clone())
.content()
.await
.map_err(|err| ToolCallError {
@@ -213,18 +211,18 @@ impl Read {
})
}
+ #[allow(deprecated)]
async fn read_document(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let mut documents = Vec::new();
for id in &self.ids {
- let document_fetcher = context
- .scribe
+ let document_fetcher = scribe
.document
- .fetch_with_auth(id, request_context.jwt_token.clone());
+ .fetch_with_auth(id, (*request_context.jwt).clone());
let document_with_content = match document_fetcher.document_content().await {
Ok(doc) => doc,
@@ -253,9 +251,10 @@ impl Read {
Ok(ReadContent::Documents { documents })
}
+ #[allow(deprecated)]
async fn read_channel(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let id = self.provide_single_id()?;
@@ -265,10 +264,9 @@ impl Read {
.map(DateTime::<Utc>::from)
.unwrap_or_else(|| chrono::Utc::now() - chrono::Duration::days(7));
// Get channel metadata
- let metadata = context
- .scribe
+ let metadata = scribe
.channel
- .get_channel_metadata(id.as_str(), Some(&request_context.jwt_token))
+ .get_channel_metadata(id.as_str(), Some(&*request_context.jwt))
.await
.map_err(|e| ToolCallError {
description: format!("failed to fetch channel metadata: {}", e),
@@ -276,12 +274,11 @@ impl Read {
})?;
// Get channel transcript
- let transcript = context
- .scribe
+ let transcript = scribe
.channel
.get_channel_transcript(
id.as_str(),
- Some(&request_context.jwt_token),
+ Some(&*request_context.jwt),
Some(since),
Some(MAX_MESSAGES),
)
@@ -298,9 +295,10 @@ impl Read {
})
}
+ #[allow(deprecated)]
async fn read_channel_message(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let mut transcripts = Vec::new();
@@ -308,10 +306,9 @@ impl Read {
for id in &self.ids {
// Get messages with context
- let transcript = match context
- .scribe
+ let transcript = match scribe
.channel
- .get_message_with_context(id.as_str(), 0, 0, &request_context.jwt_token)
+ .get_message_with_context(id.as_str(), 0, 0, &request_context.jwt)
.await
{
Ok(t) => t,
@@ -353,16 +350,16 @@ impl Read {
})
}
+ #[allow(deprecated)]
async fn read_chat_thread(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let id = self.provide_single_id()?;
- let history = context
- .scribe
+ let history = scribe
.chat
- .get_chat_history(&id, Some(&request_context.jwt_token))
+ .get_chat_history(&id, Some(&*request_context.jwt))
.await
.map_err(|e| ToolCallError {
description: format!("failed to fetch chat thread: {}", e),
@@ -372,17 +369,17 @@ impl Read {
Ok(ReadContent::Chat { history })
}
+ #[allow(deprecated)]
async fn read_chat_messages(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let message_ids = &self.ids;
- let history = context
- .scribe
+ let history = scribe
.chat
- .get_chat_history_for_messages(message_ids, Some(&request_context.jwt_token))
+ .get_chat_history_for_messages(message_ids, Some(&*request_context.jwt))
.await
.map_err(|e| ToolCallError {
description: format!("failed to fetch chat messages: {}", e),
@@ -392,16 +389,16 @@ impl Read {
Ok(ReadContent::Chat { history })
}
+ #[allow(deprecated)]
async fn read_email_thread(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let id = self.provide_single_id()?;
- let messages = context
- .scribe
+ let messages = scribe
.email
- .get_email_messages_by_thread_id(&id, 0, 100, Some(&request_context.jwt_token))
+ .get_email_messages_by_thread_id(&id, 0, 100, Some(&*request_context.jwt))
.await
.map_err(|e| ToolCallError {
description: format!("failed to fetch email thread messages: {}", e),
@@ -418,9 +415,10 @@ impl Read {
})
}
+ #[allow(deprecated)]
async fn read_email_message(
&self,
- context: &ToolServiceContext,
+ scribe: &ToolScribe,
request_context: &RequestContext,
) -> Result<ReadContent, ToolCallError> {
let mut email_messages = Vec::new();
@@ -428,10 +426,9 @@ impl Read {
let mut thread_id = String::new();
for id in &self.ids {
- let parsed_message = match context
- .scribe
+ let parsed_message = match scribe
.email
- .get_email_message_by_id(id, Some(&request_context.jwt_token))
+ .get_email_message_by_id(id, Some(&*request_context.jwt))
.await
{
Ok(msg) => msg,
diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
index 02cc7e3de1..cbbe60610b 100644
--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
@@ -1,14 +1,15 @@
use super::types::AIDiffResponse;
use super::types::{PROMPT, REWRITE_MODEL};
-use crate::tool_context::{RequestContext, ToolScribe, ToolServiceContext};
+use crate::tool_context::ToolScribe;
use ai::types::{MessageBuilder, RequestBuilder};
use ai_format::document::Document;
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use anyhow::Error;
use async_trait::async_trait;
use model::document::FileType;
use schemars::JsonSchema;
use serde::Deserialize;
+use std::sync::Arc;
#[derive(Deserialize, JsonSchema, Debug, Clone)]
#[schemars(
@@ -27,22 +28,23 @@ pub struct MarkdownRewrite {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for MarkdownRewrite {
+impl AsyncTool<Arc<ToolScribe>> for MarkdownRewrite {
type Output = AIDiffResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[allow(deprecated)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- sc: ToolServiceContext,
+ scribe: ServiceContext<Arc<ToolScribe>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(markdown_file_id=?self.markdown_file_id, "Rewrite params");
rewrite_markdown(
self.clone(),
- &sc.scribe,
- &request_context.user_id,
- request_context.jwt_token.clone(),
+ &scribe,
+ (*request_context.user_id).as_ref(),
+ (*request_context.jwt).clone(),
)
.await
.map_err(|err| ToolCallError {
diff --git a/rust/cloud-storage/ai_tools/src/search/mod.rs b/rust/cloud-storage/ai_tools/src/search/mod.rs
index c6af884dd6..8107285486 100644
--- a/rust/cloud-storage/ai_tools/src/search/mod.rs
+++ b/rust/cloud-storage/ai_tools/src/search/mod.rs
@@ -6,8 +6,8 @@ pub mod web;
pub fn search_toolset() -> AiToolSet {
AsyncToolSet::new()
- .add_tool::<search_service::name::NameSearch>()
+ .add_tool::<search_service::name::NameSearch, _>()
.expect("failed to add name search tool")
- .add_tool::<search_service::content::ContentSearch>()
+ .add_tool::<search_service::content::ContentSearch, _>()
.expect("failed to add content search tool")
}
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
index 4e52725aef..74c925bd93 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
@@ -1,13 +1,14 @@
use super::types::{PAGE_SIZE, SearchToolResponse};
-use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use models_search::{
MatchType,
unified::{UnifiedSearchIndex, UnifiedSearchRequest},
};
use schemars::JsonSchema;
+use search_service_client::SearchServiceClient;
use serde::Deserialize;
+use std::sync::Arc;
#[derive(Debug, JsonSchema, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
@@ -29,13 +30,13 @@ pub struct ContentSearch {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for ContentSearch {
+impl AsyncTool<Arc<SearchServiceClient>> for ContentSearch {
type Output = SearchToolResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- context: ToolServiceContext,
+ search_client: ServiceContext<Arc<SearchServiceClient>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(self=?self, "Content search params");
@@ -58,9 +59,13 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ContentSearch {
disable_recency: false,
};
- let response = context
- .search_service_client
- .search_unified(&request_context.user_id, search_request, None, PAGE_SIZE)
+ let response = search_client
+ .search_unified(
+ (*request_context.user_id).as_ref(),
+ search_request,
+ None,
+ PAGE_SIZE,
+ )
.await
.map_err(|e| ToolCallError {
description: format!("failed to perform content search: {}", e),
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
index 53af7a08fe..f5bfb5c468 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
@@ -1,13 +1,14 @@
use super::types::{PAGE_SIZE, SearchToolResponse};
-use crate::tool_context::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use models_search::{
MatchType,
unified::{UnifiedSearchIndex, UnifiedSearchRequest},
};
use schemars::JsonSchema;
+use search_service_client::SearchServiceClient;
use serde::Deserialize;
+use std::sync::Arc;
#[derive(Debug, JsonSchema, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
@@ -29,13 +30,13 @@ pub struct NameSearch {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for NameSearch {
+impl AsyncTool<Arc<SearchServiceClient>> for NameSearch {
type Output = SearchToolResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
async fn call(
&self,
- context: ToolServiceContext,
+ search_client: ServiceContext<Arc<SearchServiceClient>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(self=?self, "Name search params");
@@ -58,9 +59,13 @@ impl AsyncTool<ToolServiceContext, RequestContext> for NameSearch {
disable_recency: false,
};
- let response = context
- .search_service_client
- .search_unified(&request_context.user_id, search_request, None, PAGE_SIZE)
+ let response = search_client
+ .search_unified(
+ (*request_context.user_id).as_ref(),
+ search_request,
+ None,
+ PAGE_SIZE,
+ )
.await
.map_err(|e| ToolCallError {
description: format!("failed to perform name search: {}", e),
diff --git a/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs b/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs
index e0eaf059b1..6ca0e0a6cc 100644
--- a/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs
+++ b/rust/cloud-storage/ai_tools/src/search/web/perplexity_search.rs
@@ -1,5 +1,4 @@
-use crate::{RequestContext, ToolServiceContext};
-use ai_toolset::{AsyncTool, ToolCallError, ToolResult};
+use ai_toolset::{AsyncTool, NoContext, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -48,13 +47,13 @@ pub struct PerplexitySearch {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext, RequestContext> for PerplexitySearch {
+impl AsyncTool<NoContext> for PerplexitySearch {
type Output = SearchResults;
- #[tracing::instrument(skip_all, fields(user_id=?_request_context.user_id), err)]
+ #[tracing::instrument(skip_all, fields(user_id=?(*_request_context.user_id).as_ref()), err)]
async fn call(
&self,
- _service_context: ToolServiceContext,
+ _service_context: ServiceContext<NoContext>,
_request_context: RequestContext,
) -> ToolResult<Self::Output> {
let client = ai::web_search::PerplexityClient::from_env().map_err(|err| ToolCallError {
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 9456bab9b2..f70bb1174c 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -1,21 +1,26 @@
+use axum::extract::FromRef;
use scribe::{
ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
email::EmailClient, static_file::StaticFileClient,
};
use std::sync::Arc;
+pub use ai_toolset::RequestContext;
+
pub type ToolScribe =
ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
-#[derive(Clone)]
+/// The full service context containing all API clients.
+/// Individual tools should extract only the clients they need via `FromRef`.
+#[derive(Clone, FromRef)]
pub struct ToolServiceContext {
pub search_service_client: Arc<search_service_client::SearchServiceClient>,
pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,
pub scribe: Arc<ToolScribe>,
}
-#[derive(Debug, Clone)]
-pub struct RequestContext {
- pub user_id: String,
- pub jwt_token: String,
+impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
+ fn from_ref(_ctx: &ToolServiceContext) -> Self {
+ ai_toolset::NoContext()
+ }
}
diff --git a/rust/cloud-storage/ai_toolset/Cargo.toml b/rust/cloud-storage/ai_toolset/Cargo.toml
index ef9f160f33..39cb20ca81 100644
--- a/rust/cloud-storage/ai_toolset/Cargo.toml
+++ b/rust/cloud-storage/ai_toolset/Cargo.toml
@@ -13,3 +13,6 @@ schemars = { workspace = true }
async-trait = { workspace = true }
thiserror = { workspace = true }
anyhow = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+axum = { workspace = true }
+axum-macros = { workspace = true }
diff --git a/rust/cloud-storage/ai_toolset/src/context.rs b/rust/cloud-storage/ai_toolset/src/context.rs
new file mode 100644
index 0000000000..1f1adbcfb7
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/context.rs
@@ -0,0 +1,34 @@
+use macro_user_id::user_id::MacroUserIdStr;
+use std::ops::{Deref, DerefMut};
+use std::sync::Arc;
+
+/// Service context wrapper for shared state passed to tools.
+///
+/// This is provides access to
+/// shared application state like database connections and API clients.
+#[derive(Default, Debug, Clone, Copy)]
+pub struct ServiceContext<S>(pub S);
+
+impl<S> Deref for ServiceContext<S> {
+ type Target = S;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl<S> DerefMut for ServiceContext<S> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+}
+
+/// Request context passed into tool calls, containing per-request data like user identity.
+#[derive(Clone)]
+pub struct RequestContext {
+ /// The ID of the user making the request.
+ pub user_id: Arc<MacroUserIdStr<'static>>,
+ /// The JWT token for the request.
+ #[deprecated(note = "Do not add new dependencies on this field")]
+ pub jwt: Arc<String>,
+}
diff --git a/rust/cloud-storage/ai_toolset/src/lib.rs b/rust/cloud-storage/ai_toolset/src/lib.rs
index dd0f03424b..3a67327bf2 100644
--- a/rust/cloud-storage/ai_toolset/src/lib.rs
+++ b/rust/cloud-storage/ai_toolset/src/lib.rs
@@ -11,41 +11,79 @@
//! - Automatic JSON schema generation via `schemars`
//! - Support for both sync and async tools
//! - Toolset management for grouping related tools
+//! - Per-tool context extraction via `axum::extract::FromRef`
//!
-//! # Example
+//! # Multi-Context Toolset Example
//!
-//! ```ignore
-//! use ai_toolset::{AsyncTool, ToolResult};
+//! Tools can each consume different parts of a shared context. The `FromRef` bound
+//! ensures compile-time safety when extracting tool-specific contexts.
+//!
+//! ```
+//! use ai_toolset::{AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolResult};
+//! use axum_macros::FromRef;
//! use schemars::JsonSchema;
//! use serde::{Deserialize, Serialize};
+//! use std::sync::Arc;
//!
-//! #[derive(JsonSchema, Deserialize)]
-//! #[schemars(title = "Greet", description = "Greets a user by name")]
-//! struct GreetTool {
-//! name: String,
+//! // API traits for document and property operations
+//! #[async_trait::async_trait]
+//! trait DocumentApi: Send + Sync {
+//! async fn read(&self, id: &str) -> String;
+//! }
+//!
+//! #[async_trait::async_trait]
+//! trait PropertyApi: Send + Sync {
+//! async fn update(&self, id: &str, value: &str);
+//! }
+//!
+//! // Shared toolset context with trait object clients
+//! #[derive(Clone, FromRef)]
+//! struct AppContext {
+//! document_api: Arc<dyn DocumentApi>,
+//! property_api: Arc<dyn PropertyApi>,
//! }
//!
-//! #[derive(Serialize, JsonSchema)]
-//! struct GreetOutput {
-//! message: String,
+//! // Tool that reads a document
+//! #[derive(JsonSchema, Deserialize)]
+//! #[schemars(title = "ReadDocument", description = "Reads a document by ID")]
+//! struct ReadDocumentTool { document_id: String }
+//!
+//! #[async_trait::async_trait]
+//! impl AsyncTool<Arc<dyn DocumentApi>> for ReadDocumentTool {
+//! type Output = serde_json::Value;
+//! async fn call(&self, api: ServiceContext<Arc<dyn DocumentApi>>, _req: RequestContext) -> ToolResult<Self::Output> {
+//! let content = api.read(&self.document_id).await;
+//! Ok(serde_json::json!({"content": content}))
+//! }
//! }
//!
+//! // Tool that updates a property
+//! #[derive(JsonSchema, Deserialize)]
+//! #[schemars(title = "UpdateProperty", description = "Updates a property value")]
+//! struct UpdatePropertyTool { property_id: String, value: String }
+//!
//! #[async_trait::async_trait]
-//! impl AsyncTool<(), ()> for GreetTool {
-//! type Output = GreetOutput;
-//! async fn call(&self, _: (), _: ()) -> ToolResult<Self::Output> {
-//! Ok(GreetOutput {
-//! message: format!("Hello, {}!", self.name),
-//! })
+//! impl AsyncTool<Arc<dyn PropertyApi>> for UpdatePropertyTool {
+//! type Output = serde_json::Value;
+//! async fn call(&self, api: ServiceContext<Arc<dyn PropertyApi>>, _req: RequestContext) -> ToolResult<Self::Output> {
+//! api.update(&self.property_id, &self.value).await;
+//! Ok(serde_json::json!({"success": true}))
//! }
//! }
+//!
+//! // Build toolset with tools using different contexts
+//! let toolset = AsyncToolSet::<AppContext>::new()
+//! .add_tool::<ReadDocumentTool, Arc<dyn DocumentApi>>().unwrap()
+//! .add_tool::<UpdatePropertyTool, Arc<dyn PropertyApi>>().unwrap();
//! ```
#![deny(missing_docs)]
+mod context;
pub mod schema;
mod tool;
mod toolset;
+pub use context::*;
pub use tool::*;
pub use toolset::*;
diff --git a/rust/cloud-storage/ai_toolset/src/schema/generate.rs b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
index 3231686892..e052655e88 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/generate.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
@@ -45,7 +45,7 @@ impl ToolSchemaGenerator for ToolSchemas {
}
}
-impl<C, R> ToolSchemaGenerator for AsyncToolSet<C, R> {
+impl<Context> ToolSchemaGenerator for AsyncToolSet<Context> {
fn generate_schemas(&self) -> ToolSchemas {
let schemas = self
.tools
diff --git a/rust/cloud-storage/ai_toolset/src/tool.rs b/rust/cloud-storage/ai_toolset/src/tool.rs
index 57dd858b1c..380af14dd9 100644
--- a/rust/cloud-storage/ai_toolset/src/tool.rs
+++ b/rust/cloud-storage/ai_toolset/src/tool.rs
@@ -1,9 +1,9 @@
+use crate::{RequestContext, ServiceContext};
use async_trait::async_trait;
use serde::Serialize;
/// Result type for tool calls, containing either the output or a [`ToolCallError`].
pub type ToolResult<T> = std::result::Result<T, ToolCallError>;
-
/// A unit type for tools that don't require any context.
pub struct NoContext();
@@ -28,31 +28,20 @@ impl std::fmt::Display for ToolCallError {
}
}
-/// Trait for synchronous tools that can be called by an AI model.
-///
-/// # Type Parameters
-///
-/// - `Sc`: Service context type (shared state like database connections)
-/// - `Rc`: Request context type (per-request data like user info)
-pub trait Tool<Sc, Rc>: Sync + Send {
- /// The output type produced by this tool.
- type Output: Serialize + 'static;
-
- /// Execute the tool with the given contexts.
- fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output>;
-}
-
/// Trait for asynchronous tools that can be called by an AI model.
///
/// # Type Parameters
///
-/// - `Sc`: Service context type (shared state like database connections)
-/// - `Rc`: Request context type (per-request data like user info)
+/// - `Context`: Service context type (shared state like database connections)
#[async_trait]
-pub trait AsyncTool<Sc, Rc>: Sync + Send {
+pub trait AsyncTool<Context>: Sync + Send {
/// The output type produced by this tool.
type Output: Serialize + 'static;
/// Execute the tool asynchronously with the given contexts.
- async fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output>;
+ async fn call(
+ &self,
+ service_context: ServiceContext<Context>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output>;
}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs
index cb006448ee..f9a36b3b1d 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/json_tool.rs
@@ -1,67 +1,32 @@
-use crate::ToolCallError;
-use crate::{AsyncTool, Tool, ToolResult};
-
-/// Wrapper that converts a synchronous tool's output to JSON.
-///
-/// This wraps a [`Tool`] and serializes its output to a [`serde_json::Value`].
-pub struct JsonTool<Sc, Rc, O>(Box<dyn Tool<Sc, Rc, Output = O>>);
-
-impl<Sc, Rc, O> JsonTool<Sc, Rc, O> {
- /// Creates a new `JsonTool` from a boxed tool.
- pub fn from_boxed<T>(t: Box<T>) -> Self
- where
- T: Tool<Sc, Rc, Output = O> + 'static,
- O: serde::Serialize,
- {
- Self(t)
- }
-}
+use crate::{AsyncTool, ToolResult};
+use crate::{RequestContext, ServiceContext, ToolCallError};
/// Wrapper that converts an asynchronous tool's output to JSON.
-///
/// This wraps an [`AsyncTool`] and serializes its output to a [`serde_json::Value`].
-pub struct JsonAsyncTool<Sc, Rc, O>(Box<dyn AsyncTool<Sc, Rc, Output = O>>);
+pub struct JsonAsyncTool<Context, O>(Box<dyn AsyncTool<Context, Output = O>>);
-impl<Sc, Rc, O> JsonAsyncTool<Sc, Rc, O> {
+impl<Context, O> JsonAsyncTool<Context, O> {
/// Creates a new `JsonAsyncTool` from a boxed async tool.
pub fn from_boxed<T>(t: Box<T>) -> Self
where
- T: AsyncTool<Sc, Rc, Output = O> + 'static,
+ T: AsyncTool<Context, Output = O> + 'static,
O: serde::Serialize,
{
Self(t)
}
}
-impl<Sc, Rc, O> Tool<Sc, Rc> for JsonTool<Sc, Rc, O>
-where
- O: serde::Serialize + 'static,
-{
- type Output = serde_json::Value;
- fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<Self::Output> {
- self.0
- .call(service_context, request_context)
- .and_then(|out| {
- serde_json::to_value(out).map_err(|err| ToolCallError {
- description: "An internal error occurred".to_string(),
- internal_error: anyhow::Error::from(err),
- })
- })
- }
-}
-
#[async_trait::async_trait]
-impl<Sc, Rc, O> AsyncTool<Sc, Rc> for JsonAsyncTool<Sc, Rc, O>
+impl<Context, O> AsyncTool<Context> for JsonAsyncTool<Context, O>
where
O: serde::Serialize + 'static,
- Sc: Send + Sync,
- Rc: Send + Sync,
+ Context: Send + Sync,
{
type Output = serde_json::Value;
async fn call(
&self,
- service_context: Sc,
- request_context: Rc,
+ service_context: ServiceContext<Context>,
+ request_context: RequestContext,
) -> ToolResult<serde_json::Value> {
self.0
.call(service_context, request_context)
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs
index 7dc9e91df0..03ec363b67 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs
@@ -8,11 +8,9 @@ mod util;
mod json_tool;
mod object;
-mod tool;
mod tool_async;
pub use json_tool::*;
pub use object::*;
-pub use tool::*;
pub use tool_async::*;
pub use util::*;
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool.rs
deleted file mode 100644
index 4adc583dca..0000000000
--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use crate::Tool;
-use schemars::JsonSchema;
-use serde::Serialize;
-use serde::de::Deserialize;
-
-use super::json_tool::JsonTool;
-use super::object::{ToolObject, ValidationError};
-use super::util::validate_tool_schema;
-
-type ToolTraitObject<Sc, Rc> = Box<dyn Tool<Sc, Rc, Output = serde_json::Value> + Send + Sync>;
-
-type Deserializer<Sc, Rc> = Box<
- dyn Fn(&serde_json::Value) -> Result<ToolTraitObject<Sc, Rc>, serde_json::Error> + Send + Sync,
->;
-
-/// Type alias for a [`ToolObject`] configured for synchronous tools.
-pub type SyncToolObject<Context, RequestContext> =
- ToolObject<Deserializer<Context, RequestContext>>;
-
-impl<Sc, Rc> ToolObject<Deserializer<Sc, Rc>> {
- /// Attempts to deserialize JSON input into a callable tool instance.
- pub fn try_deserialize(
- &self,
- data: &serde_json::Value,
- ) -> Result<ToolTraitObject<Sc, Rc>, serde_json::Error> {
- let deserializer = &self.deserializer;
- deserializer(data)
- }
-
- /// Creates a new [`SyncToolObject`] from a tool type.
- ///
- /// The tool type must implement [`Tool`], [`JsonSchema`], and [`Deserialize`].
- /// Returns an error if schema validation fails.
- pub fn try_from_tool<T>() -> Result<Self, ValidationError>
- where
- T: JsonSchema + Tool<Sc, Rc> + Send + Sync + for<'de> Deserialize<'de> + 'static,
- T::Output: Serialize + JsonSchema + 'static,
- Sc: 'static,
- Rc: 'static,
- {
- let schema = generate_tool_input_schema!(&T);
-
- let (name, description) = validate_tool_schema(&schema)?;
-
- let json_schema =
- serde_json::to_value(schema.clone()).map_err(ValidationError::JsonSerialization)?;
-
- let deserializer = Box::new(|data: &serde_json::Value| {
- serde_json::from_value::<T>(data.clone()).map(|tool| {
- Box::new(JsonTool::from_boxed(Box::new(tool))) as ToolTraitObject<Sc, Rc>
- })
- });
-
- let output_schema = generate_tool_output_schema!(&T::Output);
-
- let output_json_schema =
- serde_json::to_value(output_schema).map_err(ValidationError::JsonSerialization)?;
-
- Ok(Self {
- name,
- input_schema: json_schema,
- description,
- deserializer,
- output_schema: output_json_schema,
- })
- }
-}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
index 90ac30f594..b869b32955 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
@@ -1,64 +1,135 @@
-use crate::{AsyncTool, Tool, ToolResult};
+use super::object::{ToolObject, ValidationError};
+use super::util::validate_tool_schema;
+use crate::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
+use axum::extract::FromRef;
use schemars::JsonSchema;
use serde::Serialize;
use serde::de::Deserialize;
-use super::JsonAsyncTool;
-use super::object::{ToolObject, ValidationError};
-use super::tool::SyncToolObject;
-use super::util::validate_tool_schema;
+/// Internal trait for callable tools that work directly with `ToolSetContext`.
+///
+/// This trait abstracts over the context extraction, allowing tools with different
+/// `ToolContext` types to be stored together in a single toolset.
+#[async_trait]
+pub trait ToolSetCallable<ToolSetContext>: Send + Sync {
+ /// Execute the tool with the given toolset context and request context.
+ async fn call(
+ &self,
+ context: ToolSetContext,
+ request_context: RequestContext,
+ ) -> ToolResult<serde_json::Value>;
+}
+
+/// Adapter that wraps an `AsyncTool<ToolContext>` to work with `ToolSetContext`.
+///
+/// This adapter extracts the specific `ToolContext` from `ToolSetContext` using
+/// `FromRef` before calling the underlying tool.
+struct ToolContextAdapter<ToolSetContext, ToolContext, T>
+where
+ ToolContext: FromRef<ToolSetContext>,
+{
+ tool: T,
+ _phantom: std::marker::PhantomData<fn(ToolSetContext) -> ToolContext>,
+}
+
+impl<ToolSetContext, ToolContext, T> ToolContextAdapter<ToolSetContext, ToolContext, T>
+where
+ ToolContext: FromRef<ToolSetContext>,
+{
+ fn new(tool: T) -> Self {
+ Self {
+ tool,
+ _phantom: std::marker::PhantomData,
+ }
+ }
+}
+
+#[async_trait]
+impl<ToolSetContext, ToolContext, T> ToolSetCallable<ToolSetContext>
+ for ToolContextAdapter<ToolSetContext, ToolContext, T>
+where
+ ToolSetContext: Send + Sync,
+ ToolContext: FromRef<ToolSetContext> + Send + Sync,
+ T: AsyncTool<ToolContext> + Send + Sync,
+ T::Output: Serialize,
+{
+ async fn call(
+ &self,
+ context: ToolSetContext,
+ request_context: RequestContext,
+ ) -> ToolResult<serde_json::Value> {
+ let tool_context = ToolContext::from_ref(&context);
+ self.tool
+ .call(ServiceContext(tool_context), request_context)
+ .await
+ .and_then(|out| {
+ serde_json::to_value(out).map_err(|err| ToolCallError {
+ description: "An internal error occurred".to_string(),
+ internal_error: anyhow::Error::from(err),
+ })
+ })
+ }
+}
+
+/// Trait object type for tools callable with `ToolSetContext`.
+type AsyncToolTraitObject<ToolSetContext> = Box<dyn ToolSetCallable<ToolSetContext> + Send + Sync>;
-type AsyncToolTraitObject<Sc, Rc> =
- Box<dyn AsyncTool<Sc, Rc, Output = serde_json::Value> + Send + Sync>;
-type AsyncDeserializer<Sc, Rc> = Box<
- dyn Fn(&serde_json::Value) -> Result<AsyncToolTraitObject<Sc, Rc>, serde_json::Error>
+/// Deserializer function type that creates a callable tool from JSON.
+type AsyncDeserializer<ToolSetContext> = Box<
+ dyn Fn(&serde_json::Value) -> Result<AsyncToolTraitObject<ToolSetContext>, serde_json::Error>
+ Send
+ Sync,
>;
-/// Type alias for a [`ToolObject`] configured for asynchronous tools.
-pub type AsyncToolObject<Context, RequestContext> =
- ToolObject<AsyncDeserializer<Context, RequestContext>>;
+/// Type alias for a `ToolObject` configured for asynchronous tools.
+///
+/// This tool object can hold tools with different `ToolContext` types, as long as
+/// each `ToolContext` can be extracted from `ToolSetContext` via `FromRef`.
+pub type AsyncToolObject<ToolSetContext> = ToolObject<AsyncDeserializer<ToolSetContext>>;
-impl<Sc, Rc> ToolObject<AsyncDeserializer<Sc, Rc>> {
+impl<ToolSetContext> ToolObject<AsyncDeserializer<ToolSetContext>> {
/// Attempts to deserialize JSON input into a callable async tool instance.
pub fn try_deserialize(
&self,
data: &serde_json::Value,
- ) -> Result<AsyncToolTraitObject<Sc, Rc>, serde_json::Error> {
+ ) -> Result<AsyncToolTraitObject<ToolSetContext>, serde_json::Error> {
let deserializer = &self.deserializer;
deserializer(data)
}
}
-impl<Sc, Rc> ToolObject<AsyncDeserializer<Sc, Rc>> {
- /// Creates a new [`AsyncToolObject`] from an async tool type.
+impl<ToolSetContext> ToolObject<AsyncDeserializer<ToolSetContext>>
+where
+ ToolSetContext: Send + Sync + 'static,
+{
+ /// Creates a new `AsyncToolObject` from an async tool type.
///
- /// The tool type must implement [`AsyncTool`], [`JsonSchema`], and [`Deserialize`].
- /// Returns an error if schema validation fails.
- pub fn try_from_tool<T, O>() -> Result<Self, ValidationError>
+ /// The tool type must implement `AsyncTool` with a context that can be extracted
+ /// from `ToolSetContext` using `FromRef`. The context extraction is captured at
+ /// creation time, allowing tools with different `ToolContext` types to coexist
+ /// in the same toolset.
+ pub fn try_from_tool<T, ToolContext, O>() -> Result<Self, ValidationError>
where
+ ToolContext: FromRef<ToolSetContext> + Send + Sync + 'static,
T: JsonSchema
- + AsyncTool<Sc, Rc, Output = O>
+ + AsyncTool<ToolContext, Output = O>
+ for<'de> Deserialize<'de>
+ 'static
+ Send
+ Sync,
O: Serialize + JsonSchema + 'static,
- Rc: Send + Sync + 'static,
- Sc: Send + Sync + 'static,
{
let input_schema = generate_tool_input_schema!(&T);
-
let (name, description) = validate_tool_schema(&input_schema)?;
-
let input_schema_json =
serde_json::to_value(input_schema).map_err(ValidationError::JsonSerialization)?;
let deserializer = Box::new(|data: &serde_json::Value| {
serde_json::from_value::<T>(data.clone()).map(|tool| {
- Box::new(JsonAsyncTool::from_boxed(Box::new(tool))) as AsyncToolTraitObject<Sc, Rc>
+ Box::new(ToolContextAdapter::<ToolSetContext, ToolContext, T>::new(
+ tool,
+ )) as AsyncToolTraitObject<ToolSetContext>
})
});
@@ -75,41 +146,3 @@ impl<Sc, Rc> ToolObject<AsyncDeserializer<Sc, Rc>> {
})
}
}
-
-impl<Sc, Rc> From<SyncToolObject<Sc, Rc>> for AsyncToolObject<Sc, Rc>
-where
- Sc: Send + Sync + 'static,
- Rc: Send + Sync + 'static,
-{
- fn from(value: SyncToolObject<Sc, Rc>) -> Self {
- let async_deserializer = Box::new(move |json: &serde_json::Value| {
- (value.deserializer)(json).map(|trait_obj| {
- Box::new(AsyncToolWrapper(trait_obj)) as AsyncToolTraitObject<Sc, Rc>
- })
- });
-
- Self {
- description: value.description,
- input_schema: value.input_schema,
- name: value.name,
- deserializer: async_deserializer,
- output_schema: value.output_schema,
- }
- }
-}
-
-/// Wrapper that adapts a synchronous [`Tool`] to implement [`AsyncTool`].
-pub struct AsyncToolWrapper<Sc, Rc, O>(pub Box<dyn Tool<Sc, Rc, Output = O> + Send + Sync>);
-
-#[async_trait]
-impl<Sc, Rc, O> AsyncTool<Sc, Rc> for AsyncToolWrapper<Sc, Rc, O>
-where
- Rc: Send + Sync + 'static,
- Sc: Send + Sync + 'static,
- O: Serialize + 'static,
-{
- type Output = O;
- async fn call(&self, service_context: Sc, request_context: Rc) -> ToolResult<O> {
- Tool::call(&*self.0, service_context, request_context)
- }
-}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
index 7fcaca82ba..abfbbdc0fd 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/types.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
@@ -1,5 +1,7 @@
-use super::tool_object::{AsyncToolObject, SyncToolObject, ValidationError};
-use crate::{AsyncTool, Tool, ToolResult};
+use super::tool_object::{AsyncToolObject, ValidationError};
+use crate::RequestContext;
+use crate::{AsyncTool, ToolResult};
+use axum::extract::FromRef;
use schemars::{JsonSchema, Schema};
use serde::Serialize;
use serde::de::Deserialize;
@@ -28,11 +30,8 @@ pub enum ToolSetError {
NotFound(String),
}
-/// Type alias for a toolset containing synchronous tools.
-pub type SyncToolSet<Context, RequestContext> = ToolSet<SyncToolObject<Context, RequestContext>>;
-
/// Type alias for a toolset containing asynchronous tools.
-pub type AsyncToolSet<Context, RequestContext> = ToolSet<AsyncToolObject<Context, RequestContext>>;
+pub type AsyncToolSet<ToolSetContext> = ToolSet<AsyncToolObject<ToolSetContext>>;
/// Represents the schema information for a tool.
pub struct ToolSchema {
@@ -74,52 +73,6 @@ impl<T> ToolSet<T> {
}
}
-impl<Sc, Rc> ToolSet<SyncToolObject<Sc, Rc>>
-where
- Rc: Sync + Send + 'static,
- Sc: Sync + Send + 'static,
-{
- /// Adds a synchronous tool to this toolset.
- ///
- /// The tool type must implement [`Tool`], [`JsonSchema`], and [`Deserialize`].
- /// Returns an error if schema validation fails or a tool with the same name exists.
- pub fn add_tool<T>(mut self) -> Result<Self, ToolSetCreationError>
- where
- T: JsonSchema + Tool<Sc, Rc> + for<'de> Deserialize<'de> + 'static + Send + Sync,
- T::Output: Serialize + JsonSchema + 'static,
- {
- let tool_object =
- SyncToolObject::try_from_tool::<T>().map_err(ToolSetCreationError::Validation)?;
- if self.tools.contains_key(&tool_object.name) {
- Err(ToolSetCreationError::NameConflict(tool_object.name.clone()))
- } else {
- self.tools.insert(tool_object.name.clone(), tool_object);
- Ok(self)
- }
- }
-
- /// Attempts to call a tool by name with the given JSON input.
- ///
- /// Returns an error if the tool is not found or if deserialization fails.
- pub fn try_tool_call(
- &self,
- context: Sc,
- request_context: Rc,
- tool_name: &str,
- json: &serde_json::Value,
- ) -> Result<ToolResult<serde_json::Value>, ToolSetError> {
- let tool = self
- .tools
- .get(tool_name)
- .ok_or_else(|| ToolSetError::NotFound(tool_name.to_owned()))
- .and_then(|tool| {
- tool.try_deserialize(json)
- .map_err(ToolSetError::Deserialization)
- })?;
- Ok(tool.call(context, request_context))
- }
-}
-
impl<T> ToolSet<T> {
/// Merges another toolset into this one.
///
@@ -135,40 +88,25 @@ impl<T> ToolSet<T> {
}
}
-impl<Sc, Rc> SyncToolSet<Sc, Rc>
+impl<ToolSetContext> AsyncToolSet<ToolSetContext>
where
- Sc: Send + Sync + 'static,
- Rc: Send + Sync + 'static,
-{
- /// Converts this synchronous toolset into an asynchronous toolset.
- ///
- /// Each synchronous tool is wrapped to be callable in an async context.
- pub fn into_async(self) -> AsyncToolSet<Sc, Rc> {
- AsyncToolSet {
- tools: self
- .tools
- .into_iter()
- .map(|(name, obj)| (name, AsyncToolObject::from(obj)))
- .collect(),
- }
- }
-}
-
-impl<Sc, Rc> AsyncToolSet<Sc, Rc>
-where
- Rc: Sync + Send + 'static,
- Sc: Sync + Send + 'static,
+ ToolSetContext: Sync + Send + 'static,
{
/// Adds an asynchronous tool to this toolset.
///
/// The tool type must implement [`AsyncTool`], [`JsonSchema`], and [`Deserialize`].
+ /// The tool's context type (`ToolContext`) must be extractable from `ToolSetContext`
+ /// using `FromRef`, providing a compile-time guarantee that the toolset context
+ /// can be narrowed to the specific context required by each tool.
+ ///
/// Returns an error if schema validation fails or a tool with the same name exists.
- pub fn add_tool<T>(mut self) -> Result<Self, ToolSetCreationError>
+ pub fn add_tool<T, ToolContext>(mut self) -> Result<Self, ToolSetCreationError>
where
- T: JsonSchema + AsyncTool<Sc, Rc> + for<'de> Deserialize<'de> + 'static + Send + Sync,
+ ToolContext: Sync + Send + FromRef<ToolSetContext> + 'static,
+ T: JsonSchema + AsyncTool<ToolContext> + for<'de> Deserialize<'de> + 'static + Send + Sync,
T::Output: Serialize + JsonSchema + 'static,
{
- let tool_object = AsyncToolObject::try_from_tool::<T, T::Output>()
+ let tool_object = AsyncToolObject::try_from_tool::<T, ToolContext, T::Output>()
.map_err(ToolSetCreationError::Validation)?;
if self.tools.contains_key(&tool_object.name) {
Err(ToolSetCreationError::NameConflict(tool_object.name.clone()))
@@ -180,11 +118,15 @@ where
/// Attempts to call a tool by name with the given JSON input.
///
+ /// The tool will automatically extract its specific context from the provided
+ /// `ToolSetContext` using the `FromRef` implementation captured when the tool
+ /// was added.
+ ///
/// Returns an error if the tool is not found or if deserialization fails.
pub async fn try_tool_call(
&self,
- context: Sc,
- request_context: Rc,
+ context: ToolSetContext,
+ request_context: RequestContext,
tool_name: &str,
json: &serde_json::Value,
) -> Result<ToolResult<serde_json::Value>, ToolSetError> {
@@ -199,19 +141,3 @@ where
Ok(tool.call(context, request_context).await)
}
}
-
-impl<T> std::fmt::Debug for ToolSet<T> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut list = f.debug_list();
- list.entries(self.tools.keys());
- list.finish()
- }
-}
-
-impl<T: Clone> Clone for ToolSet<T> {
- fn clone(&self) -> Self {
- Self {
- tools: self.tools.clone(),
- }
- }
-}
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 8da28364ad..773368e742 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
@@ -25,6 +25,7 @@ use ai_request::build_chat_completion_request;
use ai_tools::{AiToolSet, RequestContext, ToolServiceContext};
use anyhow::{Context, Result};
use futures::stream::StreamExt;
+use macro_user_id::user_id::MacroUserIdStr;
use model::chat::{NewAttachment, NewChatMessage};
use std::sync::Arc;
use tokio;
@@ -81,13 +82,13 @@ pub struct StreamChatResponse {
pub new_messages: Vec<ChatMessage>,
}
-#[tracing::instrument(err, skip(context, user_id, request, sender, jwt_token), fields(chat_id=?chat_id, message_id=?message_id))]
+#[tracing::instrument(err, skip(context, user_id, request, sender, jwt_token, toolset), fields(chat_id=?chat_id, message_id=?message_id))]
#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]
// Handles streaming the response from the provider back to the
// client over the websocket connection. Returns the response string
pub async fn stream_chat_response(
context: Arc<ApiContext>,
- user_id: &str,
+ user_id: Arc<MacroUserIdStr<'static>>,
request: ChatCompletionRequest,
toolset: AiToolSet,
sender: &UnboundedSender<FromWebSocketMessage>,
@@ -112,16 +113,17 @@ pub async fn stream_chat_response(
scribe: context.scribe.clone(),
};
+ #[expect(deprecated)]
let request_context = RequestContext {
- user_id: user_id.to_string(),
- jwt_token: jwt_token.to_string(),
+ user_id: user_id.clone(),
+ jwt: Arc::new(jwt_token.to_string()),
};
let client = ToolLoop::new(toolset, tool_context);
let mut chat = client.chat();
let now = std::time::Instant::now();
let mut stream = chat
- .send_message(request, request_context, user_id.to_owned())
+ .send_message(request, request_context, user_id.as_ref().to_string())
.await?;
// Process the stream completely
@@ -271,18 +273,18 @@ pub async fn store_conversation_messages(
}
/// Handles incoming messages of type `send_message`
-#[tracing::instrument(skip(ctx, sender, incoming_message, jwt_token), fields(chat_id=?incoming_message.chat_id, stream_id=?incoming_message.stream_id))]
+#[tracing::instrument(skip(ctx, sender, incoming_message, jwt_token, user_id), fields(chat_id=?incoming_message.chat_id, stream_id=?incoming_message.stream_id))]
pub async fn handle_send_chat_message(
sender: &UnboundedSender<FromWebSocketMessage>,
ctx: Arc<ApiContext>,
message_id: String,
incoming_message: SendChatMessagePayload,
- user_id: &str,
+ user_id: Arc<MacroUserIdStr<'static>>,
connection_id: &str,
jwt_token: &str,
) -> Result<(), StreamWebSocketError> {
let now = std::time::Instant::now();
- let chat = get_chat(&ctx, &incoming_message.chat_id, user_id)
+ let chat = get_chat(&ctx, &incoming_message.chat_id, user_id.0.as_ref())
.await
.map_err(|err| {
tracing::error!(error=?err, "failed to get chat");
@@ -297,15 +299,20 @@ pub async fn handle_send_chat_message(
FALLBACK_MODEL
};
- let _user_message_id =
- store_incoming_message(ctx.clone(), user_id, &chat, model, &incoming_message)
- .await
- .map_err(|err| {
- tracing::error!(error=?err, "failed to store incoming message");
- StreamError::InternalError {
- stream_id: incoming_message.stream_id.clone(),
- }
- })?;
+ let _user_message_id = store_incoming_message(
+ ctx.clone(),
+ user_id.0.as_ref(),
+ &chat,
+ model,
+ &incoming_message,
+ )
+ .await
+ .map_err(|err| {
+ tracing::error!(error=?err, "failed to store incoming message");
+ StreamError::InternalError {
+ stream_id: incoming_message.stream_id.clone(),
+ }
+ })?;
let toolset = toolset::choose_toolset(&incoming_message);
let request = build_chat_completion_request(
@@ -326,7 +333,7 @@ pub async fn handle_send_chat_message(
log::log_timing(log::LatencyMetric::TimeToSendRequest, model, now.elapsed());
let StreamChatResponse { new_messages } = stream_chat_response(
ctx.clone(),
- user_id,
+ user_id.clone(),
request,
toolset.toolset,
sender,
@@ -358,7 +365,7 @@ pub async fn handle_send_chat_message(
store_conversation_messages(
ctx.clone(),
- user_id,
+ user_id.0.as_ref(),
&incoming_message.chat_id,
new_messages,
model,
@@ -373,7 +380,7 @@ pub async fn handle_send_chat_message(
// The chat is empty and we want to auto generate a name for the chat
if is_first_message {
- let _ = maybe_rename_chat(&incoming_message.chat_id, &ctx, user_id)
+ let _ = maybe_rename_chat(&incoming_message.chat_id, &ctx, user_id.0.as_ref())
.await
.inspect_err(|err| tracing::error!(error=?err, "failed to rename chat"))
.map(|new_name| {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs
index e43fbef288..5c51276136 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs
@@ -9,7 +9,7 @@ use axum::{
response::IntoResponse,
};
use dashmap::DashMap;
-use macro_user_id::user_id::MacroUserId;
+use macro_user_id::user_id::{MacroUserId, MacroUserIdStr};
use model::{chat::AttachmentType, user::UserContext};
use models_permissions::share_permission::access_level::AccessLevel;
use std::sync::Arc;
@@ -226,10 +226,24 @@ async fn handle_websocket_connection(
continue;
}
- let user_id = user_context_clone.user_id.clone();
+ let user_id = match MacroUserIdStr::try_from(user_context_clone.user_id.clone())
+ {
+ Ok(id) => Arc::new(id),
+ Err(_) => {
+ ws_send(
+ &message_sender_clone,
+ FromWebSocketMessage::Error(WebSocketError::StreamError(
+ StreamError::InternalError {
+ stream_id: payload.stream_id.clone(),
+ },
+ )),
+ );
+ continue;
+ }
+ };
let jwt_token = payload.jwt.token.clone();
let cancel_token = cancel_token.clone();
- tracing::debug!(user_id=?user_id, chat_id=?payload.chat_id, "handling chat message");
+ tracing::debug!(user_id=?user_id.as_ref(), chat_id=?payload.chat_id, "handling chat message");
let ctx = ctx.clone();
match chat_permissions::chat_access(
&ctx,
@@ -267,7 +281,7 @@ async fn handle_websocket_connection(
ctx,
message_id,
payload,
- user_id.as_str(),
+ user_id,
&connection_id,
&jwt_token
)) => {
@@ -279,9 +293,23 @@ async fn handle_websocket_connection(
});
}
ToWebSocketMessage::EditChatMessage(payload) => {
- let user_id: String = user_context_clone.user_id.clone();
+ let user_id = match MacroUserIdStr::try_from(user_context_clone.user_id.clone())
+ {
+ Ok(id) => Arc::new(id),
+ Err(_) => {
+ ws_send(
+ &message_sender_clone,
+ FromWebSocketMessage::Error(WebSocketError::StreamError(
+ StreamError::InternalError {
+ stream_id: payload.stream_id.clone(),
+ },
+ )),
+ );
+ continue;
+ }
+ };
let jwt_token = payload.jwt.token.clone();
- tracing::debug!(user_id=?user_id, chat_id=?payload.chat_id, "handling edit message");
+ tracing::debug!(user_id=?user_id.as_ref(), chat_id=?payload.chat_id, "handling edit message");
let ctx = ctx.clone();
match chat_permissions::chat_access(
@@ -316,7 +344,7 @@ async fn handle_websocket_connection(
ctx,
&message_sender_clone,
payload,
- user_id.as_str(),
+ user_id,
&connection_id,
&jwt_token,
)
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs
index f27fa1e2a0..517a4d2ab9 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs
@@ -5,6 +5,7 @@ use crate::{
};
use macro_db_client::dcs::delete_chat_message::delete_chat_message;
+use macro_user_id::user_id::MacroUserIdStr;
use super::chat_message::handle_send_chat_message;
use super::connection::ws_send;
@@ -14,21 +15,21 @@ use std::sync::Arc;
use tokio;
use tokio::sync::mpsc::UnboundedSender;
-#[tracing::instrument(skip(ctx, sender, jwt_token, incoming_message))]
+#[tracing::instrument(skip(ctx, sender, jwt_token, incoming_message, user_id))]
pub async fn handle_edit_last_user_message(
ctx: Arc<ApiContext>,
sender: &UnboundedSender<FromWebSocketMessage>,
incoming_message: SendChatMessagePayload,
- user_id: &str,
+ user_id: Arc<MacroUserIdStr<'static>>,
connection_id: &str,
jwt_token: &str,
) -> Result<(), StreamWebSocketError> {
- let chat = get_chat(&ctx, &incoming_message.chat_id, user_id)
+ let chat = get_chat(&ctx, &incoming_message.chat_id, user_id.0.as_ref())
.await
.map_err(|err| {
tracing::error!(
chat_id = %incoming_message.chat_id,
- user_id,
+ user_id = %user_id,
error = %err,
"failed to get chat"
);
@@ -69,7 +70,7 @@ pub async fn handle_edit_last_user_message(
let mut tsx = ctx.db.begin().await.map_err(|err| {
tracing::error!(
chat_id = %incoming_message.chat_id,
- user_id,
+ user_id = %user_id,
error = %err,
"error creating transaction"
);
@@ -88,7 +89,7 @@ pub async fn handle_edit_last_user_message(
tracing::error!(
chat_id = %incoming_message.chat_id,
message_id = %first.id,
- user_id,
+ user_id = %user_id,
error = %err,
"failed to delete message (i)"
);
@@ -107,7 +108,7 @@ pub async fn handle_edit_last_user_message(
tracing::error!(
chat_id = %incoming_message.chat_id,
message_id = %last.id,
- user_id,
+ user_id = %user_id,
error = %err,
"failed to delete message (ii)"
);
@@ -122,7 +123,7 @@ pub async fn handle_edit_last_user_message(
tsx.commit().await.map_err(|err| {
tracing::error!(
chat_id = %incoming_message.chat_id,
- user_id,
+ user_id = %user_id,
error = %err,
"error committing transaction"
);
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index dc8f638d18..f6363f2f31 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -97,6 +97,16 @@ impl<'a> MacroUserIdStr<'a> {
}
}
+impl<'a> From<MacroUserIdStr<'a>> for MacroUserId<String> {
+ fn from(value: MacroUserIdStr<'a>) -> Self {
+ MacroUserId {
+ email_part: value.email_part,
+ email_part_offset: value.email_part_offset,
+ user_id: value.0.user_id.as_ref().into(),
+ }
+ }
+}
+
impl MacroUserIdStr<'static> {
/// Create a MacroUserIdStr from an email address by prepending "macro|"
pub fn try_from_email(email: &str) -> Result<Self, ParseErr> {