Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat (ai): Enumerated errors for chat (#121)
Eric Hayes550050960425
diff --git a/js/app/packages/core/component/AI/util/handleError.ts b/js/app/packages/core/component/AI/util/handleError.tsindex dbb985029d..a97ea201b3 100644--- a/js/app/packages/core/component/AI/util/handleError.ts+++ b/js/app/packages/core/component/AI/util/handleError.ts@@ -6,6 +6,8 @@ export function handleError(error: StreamError) {const { showPaywall } = usePaywallState();if (error.stream_error === 'payment_required') {showPaywall();+ } else if (error.stream_error === 'model_context_overflow') {+ toast.failure('Too much context. Remove attachments or start a new chat');} else {toast.failure('Failed to respond to message');}diff --git a/js/app/packages/service-cognition/generated/schemas/streamErrorOneOfThree.ts b/js/app/packages/service-cognition/generated/schemas/streamErrorOneOfThree.tsindex 06a6dfc5ec..ef6f412eca 100644--- a/js/app/packages/service-cognition/generated/schemas/streamErrorOneOfThree.ts+++ b/js/app/packages/service-cognition/generated/schemas/streamErrorOneOfThree.ts@@ -4,11 +4,9 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { Model } from './model';import type { StreamErrorOneOfThreeStreamError } from './streamErrorOneOfThreeStreamError';export type StreamErrorOneOfThree = {- model: Model;stream_error: StreamErrorOneOfThreeStreamError;stream_id: string;};diff --git a/js/app/packages/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-cognition/generated/tools/schemas.tsindex 64d2f3efdb..05cc395ada 100644--- a/js/app/packages/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-cognition/generated/tools/schemas.ts@@ -64,11 +64,11 @@ export const ReadOutputSchema = z.object({ "content": z.any().superRefine((x, ct}) })-export const UnifiedSearchInputSchema = z.object({ "exhaustiveSearch": z.boolean().default(true), "pageOffset": z.number().int().default(0), "pageSize": z.number().int().default(10), "request": z.object({ "filters": z.union([z.object({ "channel": z.union([z.object({ "channel_ids": z.array(z.string()), "mentions": z.array(z.string()), "org_id": z.union([z.number().int(), z.null()]), "sender_ids": z.array(z.string()), "thread_ids": z.array(z.string()) }).strict(), z.null()]), "chat": z.union([z.object({ "chat_ids": z.array(z.string()), "owners": z.array(z.string()), "project_ids": z.array(z.string()), "role": z.array(z.string()) }).strict(), z.null()]), "document": z.union([z.object({ "document_ids": z.array(z.string()), "file_types": z.array(z.string()), "owners": z.array(z.string()), "project_ids": z.array(z.string()) }).strict(), z.null()]), "email": z.union([z.object({ "bcc": z.array(z.string()), "cc": z.array(z.string()), "recipients": z.array(z.string()), "senders": z.array(z.string()) }).strict(), z.null()]), "project": z.union([z.object({ "owners": z.array(z.string()), "project_ids": z.array(z.string()) }).strict(), z.null()]) }).strict(), z.null()]), "include": z.array(z.enum(["documents","chats","emails","channels","projects"])).default([]), "match_type": z.enum(["exact","partial","regexp"]), "name_only": z.union([z.boolean(), z.null()]), "terms": z.union([z.array(z.string()), z.null()]) }).strict() }).strict()+export const UnifiedSearchInputSchema = z.object({ "exhaustiveSearch": z.boolean().default(true), "pageOffset": z.number().int().default(0), "pageSize": z.number().int().default(10), "request": z.object({ "filters": z.union([z.object({ "channel": z.union([z.object({ "channel_ids": z.array(z.string()), "mentions": z.array(z.string()), "org_id": z.union([z.number().int(), z.null()]), "sender_ids": z.array(z.string()), "thread_ids": z.array(z.string()) }).strict(), z.null()]), "chat": z.union([z.object({ "chat_ids": z.array(z.string()), "owners": z.array(z.string()), "project_ids": z.array(z.string()), "role": z.array(z.string()) }).strict(), z.null()]), "document": z.union([z.object({ "document_ids": z.array(z.string()), "file_types": z.array(z.string()), "owners": z.array(z.string()), "project_ids": z.array(z.string()) }).strict(), z.null()]), "email": z.union([z.object({ "bcc": z.array(z.string()), "cc": z.array(z.string()), "recipients": z.array(z.string()), "senders": z.array(z.string()) }).strict(), z.null()]), "project": z.union([z.object({ "owners": z.array(z.string()), "project_ids": z.array(z.string()) }).strict(), z.null()]) }).strict(), z.null()]), "include": z.array(z.enum(["documents","chats","emails","channels","projects"])).default([]), "match_type": z.enum(["exact","partial","regexp"]), "search_on": z.enum(["name","content","name_content"]).default("content"), "terms": z.union([z.array(z.string()), z.null()]) }).strict() }).strict()export const UnifiedSearchOutputSchema = z.object({ "response": z.object({ "results": z.array(z.any().superRefine((x, ctx) => {- const schemas = [z.object({ "content": z.union([z.array(z.string()), z.null()]).optional(), "document_id": z.string(), "document_name": z.string(), "file_type": z.string(), "node_id": z.string(), "owner_id": z.string(), "raw_content": z.union([z.string(), z.null()]).optional(), "type": z.literal("document"), "updated_at": z.string().datetime({ offset: true }) }), z.object({ "chat_id": z.string(), "chat_message_id": z.string(), "content": z.union([z.array(z.string()), z.null()]).optional(), "role": z.string(), "title": z.string(), "type": z.literal("chat"), "updated_at": z.string().datetime({ offset: true }), "user_id": z.string() }), z.object({ "bcc": z.array(z.string()), "cc": z.array(z.string()), "content": z.union([z.array(z.string()), z.null()]).optional(), "labels": z.array(z.string()), "link_id": z.string(), "message_id": z.string(), "recipients": z.array(z.string()), "sender": z.string(), "sent_at": z.union([z.string().datetime({ offset: true }), z.null()]).optional(), "subject": z.union([z.string(), z.null()]).optional(), "thread_id": z.string(), "type": z.literal("email"), "updated_at": z.string().datetime({ offset: true }), "user_id": z.string() }), z.object({ "channel_id": z.string(), "channel_name": z.union([z.string(), z.null()]).optional(), "channel_type": z.string(), "content": z.union([z.array(z.string()), z.null()]).optional(), "created_at": z.string().datetime({ offset: true }), "mentions": z.array(z.string()), "message_id": z.string(), "org_id": z.union([z.number().int(), z.null()]).optional(), "sender_id": z.string(), "thread_id": z.union([z.string(), z.null()]).optional(), "type": z.literal("channel"), "updated_at": z.string().datetime({ offset: true }) }), z.object({ "content": z.union([z.array(z.string()), z.null()]).optional(), "created_at": z.string().datetime({ offset: true }), "parent_project_id": z.union([z.string(), z.null()]).optional(), "project_id": z.string(), "project_name": z.string(), "type": z.literal("project"), "updated_at": z.string().datetime({ offset: true }), "user_id": z.string() })];+ const schemas = [z.object({ "document_id": z.string(), "document_name": z.string(), "file_type": z.string(), "highlight": z.object({ "content": z.array(z.string()).optional(), "name": z.union([z.string(), z.null()]).optional() }), "node_id": z.string(), "owner_id": z.string(), "raw_content": z.union([z.string(), z.null()]).optional(), "type": z.literal("document"), "updated_at": z.string().datetime({ offset: true }) }), z.object({ "chat_id": z.string(), "chat_message_id": z.string(), "highlight": z.object({ "content": z.array(z.string()).optional(), "name": z.union([z.string(), z.null()]).optional() }), "role": z.string(), "title": z.string(), "type": z.literal("chat"), "updated_at": z.string().datetime({ offset: true }), "user_id": z.string() }), z.object({ "bcc": z.array(z.string()), "cc": z.array(z.string()), "highlight": z.object({ "content": z.array(z.string()).optional(), "name": z.union([z.string(), z.null()]).optional() }), "labels": z.array(z.string()), "link_id": z.string(), "message_id": z.string(), "recipients": z.array(z.string()), "sender": z.string(), "sent_at": z.union([z.string().datetime({ offset: true }), z.null()]).optional(), "subject": z.union([z.string(), z.null()]).optional(), "thread_id": z.string(), "type": z.literal("email"), "updated_at": z.string().datetime({ offset: true }), "user_id": z.string() }), z.object({ "channel_id": z.string(), "channel_name": z.union([z.string(), z.null()]).optional(), "channel_type": z.string(), "created_at": z.string().datetime({ offset: true }), "highlight": z.object({ "content": z.array(z.string()).optional(), "name": z.union([z.string(), z.null()]).optional() }), "mentions": z.array(z.string()), "message_id": z.string(), "org_id": z.union([z.number().int(), z.null()]).optional(), "sender_id": z.string(), "thread_id": z.union([z.string(), z.null()]).optional(), "type": z.literal("channel"), "updated_at": z.string().datetime({ offset: true }) }), z.object({ "created_at": z.string().datetime({ offset: true }), "highlight": z.object({ "content": z.array(z.string()).optional(), "name": z.union([z.string(), z.null()]).optional() }), "project_id": z.string(), "project_name": z.string(), "type": z.literal("project"), "updated_at": z.string().datetime({ offset: true }), "user_id": z.string() })];const errors = schemas.reduce<z.ZodError[]>((errors, schema) =>((result) =>diff --git a/js/app/packages/service-cognition/generated/tools/types.ts b/js/app/packages/service-cognition/generated/tools/types.tsindex 831163aa39..e68c10eb62 100644--- a/js/app/packages/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-cognition/generated/tools/types.ts@@ -484,9 +484,9 @@ export interface UnifiedSearchInput {*/match_type: 'exact' | 'partial' | 'regexp';/**- * If true, match the `terms` field on name only. If false, names will not be matched on in the search. False by default.+ * Fields to search on (Name, Content, NameContent). Defaults to Content*/- name_only: boolean | null;+ search_on: 'name' | 'content' | 'name_content';/*** Multiple distinct search terms as separate strings. Use this for keyword-based searches where you want to find content containing any of these terms. Each term must be at least 3 characters (shorter terms are automatically filtered out). Examples: ['machine', 'learning', 'algorithms'], ['project', 'status', 'update']. `null` this field if searching without text terms to search all. This field matches query string against both name and content.*/@@ -512,10 +512,6 @@ export interface UnifiedSearchOutput {*/results: (| {- /**- * The opensearch matches on the document- */- content?: string[] | null;/*** The document id*/@@ -528,6 +524,19 @@ export interface UnifiedSearchOutput {* The file type*/file_type: string;+ /**+ * The highlights on the document+ */+ highlight: {+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ };/*** The node id*/@@ -556,9 +565,18 @@ export interface UnifiedSearchOutput {*/chat_message_id: string;/**- * The opensearch matches on the chat+ * The highlights on the chat*/- content?: string[] | null;+ highlight: {+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ };/*** The role*/@@ -587,9 +605,18 @@ export interface UnifiedSearchOutput {*/cc: string[];/**- * The opensearch matches on the email+ * The highlights on the email*/- content?: string[] | null;+ highlight: {+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ };/*** The labels*/@@ -645,14 +672,23 @@ export interface UnifiedSearchOutput {* The channel type*/channel_type: string;- /**- * The opensearch matches on the channel message- */- content?: string[] | null;/*** The time the channel message was created*/created_at: string;+ /**+ * The highlights on the channel message+ */+ highlight: {+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ };/*** The mentions*/@@ -680,18 +716,23 @@ export interface UnifiedSearchOutput {updated_at: string;}| {- /**- * The opensearch matches on the project- */- content?: string[] | null;/*** The time the project was created*/created_at: string;/**- * The parent project id- */- parent_project_id?: string | null;+ * The highlights on the project+ */+ highlight: {+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ };/*** The project id*/diff --git a/js/app/packages/service-cognition/openapi.json b/js/app/packages/service-cognition/openapi.jsonindex b156cf27e9..c51ebdd3ac 100644--- a/js/app/packages/service-cognition/openapi.json+++ b/js/app/packages/service-cognition/openapi.json@@ -2674,9 +2674,8 @@},{"type": "object",- "required": ["stream_id", "model", "stream_error"],+ "required": ["stream_id", "stream_error"],"properties": {- "model": { "$ref": "#/components/schemas/Model" },"stream_error": {"type": "string","enum": ["model_context_overflow"]diff --git a/rust/cloud-storage/ai/src/tool/client/chained.rs b/rust/cloud-storage/ai/src/tool/client/chained.rsindex 0deafb7b5e..e34f0f218c 100644--- a/rust/cloud-storage/ai/src/tool/client/chained.rs+++ b/rust/cloud-storage/ai/src/tool/client/chained.rs@@ -20,9 +20,8 @@ use crate::tool::types::{ChatCompletionStream, ToolResponse};use crate::types::Client;use crate::types::openai::message::convert_message;use crate::types::{- ChatCompletionRequest, ChatMessage, ChatMessages, MessageBuilder, SystemPrompt,+ ChatCompletionRequest, ChatMessage, ChatMessages, MessageBuilder, Result, SystemPrompt,};-use anyhow::Result;use async_openai::types::{ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,@@ -154,7 +153,8 @@ whereasync fn route_chained_calls(&self, part: ToolCall) -> Result<ToolCall> {tracing::debug!("route chained call {:#?}", part);let chained: ChainedTool = serde_json::from_value(part.json)- .inspect_err(|_| tracing::warn!("AI returned an invalid chained tool"))?;+ .inspect_err(|_| tracing::warn!("AI returned an invalid chained tool"))+ .map_err(anyhow::Error::from)?;let selected_tool = self.toolset@@ -407,7 +407,7 @@ wheretool_calls = HashMap::new();}}- Err(error) => yield Err(anyhow::Error::from(error)),+ Err(error) => yield Err(error.into()),}}}))diff --git a/rust/cloud-storage/ai/src/tool/client/chat.rs b/rust/cloud-storage/ai/src/tool/client/chat.rsindex a49cd132d7..8982a13744 100644--- a/rust/cloud-storage/ai/src/tool/client/chat.rs+++ b/rust/cloud-storage/ai/src/tool/client/chat.rs@@ -4,8 +4,7 @@ use crate::tool::types::{ChatCompletionStream, ToolResponse};use crate::types::openai::message::convert_message;use crate::types::{ChatCompletionRequest, ChatMessage, ChatMessages};-use crate::types::{Client, RequestExtensions};-use anyhow::Result;+use crate::types::{Client, RequestExtensions, Result};use async_openai::types::{ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,@@ -324,7 +323,7 @@ wheretool_calls = HashMap::new();}}- Err(error) => yield Err(anyhow::Error::from(error)),+ Err(error) => yield Err(error.into()),}}}))diff --git a/rust/cloud-storage/ai/src/tool/completion.rs b/rust/cloud-storage/ai/src/tool/completion.rsindex 679e97c5a9..a2a283ad2d 100644--- a/rust/cloud-storage/ai/src/tool/completion.rs+++ b/rust/cloud-storage/ai/src/tool/completion.rs@@ -1,7 +1,7 @@use super::types::ToolCall;use super::types::tool_object::ToolObject;+use crate::types::{AiError, Result};use crate::types::{ChatCompletionRequest, OpenRouterClient};-use anyhow::Result;use async_openai::types::{ChatCompletionTool, ChatCompletionToolChoiceOption, CreateChatCompletionRequest,};@@ -22,15 +22,15 @@ pub async fn tool_completion<T>(response.choices.first()- .ok_or_else(|| anyhow::anyhow!("No choices"))+ .ok_or_else(|| anyhow::anyhow!("No choices").into()).and_then(|choice| {let call = choice.message.tool_calls.as_ref()- .ok_or_else(|| anyhow::anyhow!("No tool calls"))?+ .ok_or_else(|| AiError::from(anyhow::anyhow!("No tool calls")))?.first()- .ok_or_else(|| anyhow::anyhow!("No tool calls"))?;+ .ok_or_else(|| AiError::from(anyhow::anyhow!("No tool calls")))?;Ok(ToolCall {id: call.id.clone(),json: serde_json::from_str(&call.function.arguments)?,diff --git a/rust/cloud-storage/ai/src/tool/types/stream.rs b/rust/cloud-storage/ai/src/tool/types/stream.rsindex 29f53ca4d3..0d9de1d4ab 100644--- a/rust/cloud-storage/ai/src/tool/types/stream.rs+++ b/rust/cloud-storage/ai/src/tool/types/stream.rs@@ -1,10 +1,10 @@-use crate::types::Usage;+use crate::types::{AiError, Usage};use futures::stream::Stream;use serde::Serialize;use std::pin::Pin;pub type ChatCompletionStream<'a> =- Pin<Box<dyn Stream<Item = Result<StreamPart, anyhow::Error>> + Send + 'a>>;+ Pin<Box<dyn Stream<Item = Result<StreamPart, AiError>> + Send + 'a>>;#[derive(Debug, Clone)]pub enum StreamPart {diff --git a/rust/cloud-storage/ai/src/types/client/anthropic.rs b/rust/cloud-storage/ai/src/types/client/anthropic.rsindex d2da979e49..f10adab210 100644--- a/rust/cloud-storage/ai/src/types/client/anthropic.rs+++ b/rust/cloud-storage/ai/src/types/client/anthropic.rs@@ -1,4 +1,5 @@use super::Client;+use crate::types::AiError;#[derive(Clone, Debug)]pub struct AnthropicClient {@@ -23,7 +24,7 @@ impl Client for AnthropicClient {&self,request: async_openai::types::CreateChatCompletionRequest,extensions: Option<super::RequestExtensions>,- ) -> anyhow::Result<async_openai::types::ChatCompletionResponseStream> {+ ) -> Result<async_openai::types::ChatCompletionResponseStream, AiError> {if extensions.is_some() {tracing::warn!("extensions are not yet supported");}diff --git a/rust/cloud-storage/ai/src/types/client/noop.rs b/rust/cloud-storage/ai/src/types/client/noop.rsindex 5f19f2dd24..11939d21d9 100644--- a/rust/cloud-storage/ai/src/types/client/noop.rs+++ b/rust/cloud-storage/ai/src/types/client/noop.rs@@ -1,4 +1,5 @@use super::traits::Client;+use crate::types::AiError;use anyhow::anyhow;#[derive(Debug, Clone, Default)]@@ -9,7 +10,7 @@ impl Client for NoOpClient {&self,_: async_openai::types::CreateChatCompletionRequest,_: Option<super::RequestExtensions>,- ) -> anyhow::Result<async_openai::types::ChatCompletionResponseStream> {- Err(anyhow!("noop"))+ ) -> Result<async_openai::types::ChatCompletionResponseStream, AiError> {+ Err(anyhow!("noop").into())}}diff --git a/rust/cloud-storage/ai/src/types/client/openrouter/client.rs b/rust/cloud-storage/ai/src/types/client/openrouter/client.rsindex 59977bc15e..61fd88d73b 100644--- a/rust/cloud-storage/ai/src/types/client/openrouter/client.rs+++ b/rust/cloud-storage/ai/src/types/client/openrouter/client.rs@@ -1,6 +1,7 @@use super::config::OpenRouterConfig;use crate::types::client::traits::{Client, RequestExtensions};-use crate::types::{Model, ModelWithMetadataAndProvider};+use crate::types::{AiError, Model, ModelWithMetadataAndProvider};+use anyhow::Context;use async_openai::Client as OpenAiClient;use async_openai::types::CreateChatCompletionRequest;@@ -48,7 +49,7 @@ impl Client for OpenRouterClient {&self,request: async_openai::types::CreateChatCompletionRequest,extensions: Option<RequestExtensions>,- ) -> anyhow::Result<async_openai::types::ChatCompletionResponseStream> {+ ) -> Result<async_openai::types::ChatCompletionResponseStream, AiError> {let request = self.preprocess_request(request);let request = if let Some(ext) = extensions {self.extend_request(request, ext)@@ -59,6 +60,6 @@ impl Client for OpenRouterClient {.chat().create_stream_byot(request).await- .map_err(anyhow::Error::from)+ .map_err(AiError::from)}}diff --git a/rust/cloud-storage/ai/src/types/client/traits.rs b/rust/cloud-storage/ai/src/types/client/traits.rsindex 53888f95b4..2cc0faa33a 100644--- a/rust/cloud-storage/ai/src/types/client/traits.rs+++ b/rust/cloud-storage/ai/src/types/client/traits.rs@@ -1,3 +1,4 @@+use crate::types::AiError;use anyhow::{Context, Result};use async_openai::types::{ChatCompletionResponseStream, CreateChatCompletionRequest};use serde::Serialize;@@ -24,7 +25,7 @@ pub trait Client {&self,request: CreateChatCompletionRequest,extensions: Option<RequestExtensions>,- ) -> impl Future<Output = Result<ChatCompletionResponseStream>> + Send;+ ) -> impl Future<Output = Result<ChatCompletionResponseStream, AiError>> + Send;fn extend_request(&self,diff --git a/rust/cloud-storage/ai/src/types/error.rs b/rust/cloud-storage/ai/src/types/error.rsnew file mode 100644index 0000000000..a095651fe0--- /dev/null+++ b/rust/cloud-storage/ai/src/types/error.rs@@ -0,0 +1,23 @@+use thiserror::Error;++pub type Result<T> = std::result::Result<T, AiError>;++#[derive(Debug, Error)]+pub enum AiError {+ #[error("Context is too large for current model")]+ ContextWindowExceeded,+ #[error("Unknown error")]+ Generic(anyhow::Error),+}++impl From<anyhow::Error> for AiError {+ fn from(value: anyhow::Error) -> Self {+ Self::Generic(value)+ }+}++impl From<serde_json::Error> for AiError {+ fn from(value: serde_json::Error) -> Self {+ Self::Generic(value.into())+ }+}diff --git a/rust/cloud-storage/ai/src/types/mod.rs b/rust/cloud-storage/ai/src/types/mod.rsindex c6d8072d9b..aff1b02e5a 100644--- a/rust/cloud-storage/ai/src/types/mod.rs+++ b/rust/cloud-storage/ai/src/types/mod.rs@@ -1,4 +1,5 @@mod client;+mod error;mod message;mod model;mod providers;@@ -7,6 +8,7 @@ mod request_builder;mod response;pub use client::*;+pub use error::*;pub use message::*;pub use model::*;pub(crate) use providers::*;diff --git a/rust/cloud-storage/ai/src/types/providers/openai/error.rs b/rust/cloud-storage/ai/src/types/providers/openai/error.rsnew file mode 100644index 0000000000..12b99e462f--- /dev/null+++ b/rust/cloud-storage/ai/src/types/providers/openai/error.rs@@ -0,0 +1,18 @@+use crate::types::AiError;+use async_openai::error::OpenAIError;++impl From<OpenAIError> for AiError {+ fn from(value: OpenAIError) -> Self {+ match &value {+ OpenAIError::ApiError(api_err) => {+ // for anthropic error formatting+ if api_err.message.contains("tokens >") {+ Self::ContextWindowExceeded+ } else {+ Self::Generic(value.into())+ }+ }+ _ => Self::Generic(value.into()),+ }+ }+}diff --git a/rust/cloud-storage/ai/src/types/providers/openai/mod.rs b/rust/cloud-storage/ai/src/types/providers/openai/mod.rsindex f9babf846e..e79e301cdc 100644--- a/rust/cloud-storage/ai/src/types/providers/openai/mod.rs+++ b/rust/cloud-storage/ai/src/types/providers/openai/mod.rs@@ -1,169 +1,7 @@-use crate::traits::Metadata;-use crate::types::openai::message::order_messages_tool_calls;-use crate::types::{ChatCompletionRequest, response::ChatStreamCompletionResponse};-use anyhow::Context;-use async_openai::types::{- ChatCompletionRequestMessage, ChatCompletionRequestMessageContentPartText,- ChatCompletionRequestSystemMessage, ChatCompletionRequestSystemMessageContent,- ChatCompletionRequestSystemMessageContentPart, CreateChatCompletionRequest,- CreateChatCompletionRequestArgs, CreateChatCompletionStreamResponse,- FinishReason as OpenAIFinishReason, ReasoningEffort, ResponseFormat, ResponseFormatJsonSchema,-};-use schemars::{JsonSchema, schema_for};-use serde::Deserialize;-pub mod message;--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),- name: None,- });-- let messages: Vec<ChatCompletionRequestMessage> = self- .messages- .clone()- .into_iter()- .flat_map(Vec::<ChatCompletionRequestMessage>::from)- .collect();-- all_messages.push(system_message);- all_messages.extend(messages);- all_messages- }-}--/// OPENAI-impl TryFrom<ChatCompletionRequest> for CreateChatCompletionRequest {- type Error = anyhow::Error;-- 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),- name: None,- });-- let messages: Vec<ChatCompletionRequestMessage> = value- .messages- .into_iter()- .flat_map(Vec::<ChatCompletionRequestMessage>::from)- .collect();- let messages = order_messages_tool_calls(messages);-- all_messages.push(system_message);- all_messages.extend(messages);-- let model = value.model.to_string();-- Ok(if value.model.to_string().starts_with("o") {- CreateChatCompletionRequestArgs::default()- .model(model)- .reasoning_effort(ReasoningEffort::High)- .messages(all_messages)- .build()?- } else {- CreateChatCompletionRequestArgs::default()- .model(model)- .reasoning_effort(ReasoningEffort::Medium)- .messages(all_messages)- .build()?- })- }-}--// Response-impl TryFrom<CreateChatCompletionStreamResponse> for ChatStreamCompletionResponse {- type Error = anyhow::Error;-- fn try_from(value: CreateChatCompletionStreamResponse) -> anyhow::Result<Self> {- let choices = value.choices.first().context("no choices");- let content = if let Ok(choices) = choices {- let content = choices.delta.content.clone().unwrap_or("".to_string());- if let Some(finish_reason) = choices.finish_reason {- match finish_reason {- OpenAIFinishReason::Stop => {}- _ => {- tracing::error!(- "unexpected finish reason for openai response: {:?}",- finish_reason,- );- }- }- }- content- } else {- String::new()- };- Ok(ChatStreamCompletionResponse::new_content(- content,- value.usage,- ))- }-}--impl ChatCompletionRequest {- /// misnomer this actually uses the -- tools api- pub fn as_structured_request<S>(- self,- stream: bool,- ) -> anyhow::Result<CreateChatCompletionRequest>- where- S: JsonSchema + Metadata + for<'de> Deserialize<'de>,- {- let schema = schema_for!(S);- let json_schema = serde_json::to_value(schema).context("failed to form json_schema")?;- tracing::debug!(- "{}",- serde_json::to_string_pretty(&json_schema).expect("json_string")- );-- let response_format = ResponseFormat::JsonSchema {- json_schema: ResponseFormatJsonSchema {- description: S::description(),- name: S::name(),- schema: Some(json_schema),- strict: Some(true),- },- };-- CreateChatCompletionRequestArgs::default()- .stream(stream)- .model(self.model.to_string())- .messages(self.openai_messages())- .response_format(response_format)- .build()- .context("Could not build openai request")- }-}+mod error;+pub(crate) mod message;+mod request;+mod response;#[cfg(test)]mod test {diff --git a/rust/cloud-storage/ai/src/types/providers/openai/request.rs b/rust/cloud-storage/ai/src/types/providers/openai/request.rsnew file mode 100644index 0000000000..e4ac8a4a36--- /dev/null+++ b/rust/cloud-storage/ai/src/types/providers/openai/request.rs@@ -0,0 +1,80 @@+use crate::traits::Metadata;+use crate::types::ChatCompletionRequest;+use anyhow::Context;+use async_openai::types::{+ ChatCompletionRequestMessage, ChatCompletionRequestMessageContentPartText,+ ChatCompletionRequestSystemMessage, ChatCompletionRequestSystemMessageContent,+ ChatCompletionRequestSystemMessageContentPart, CreateChatCompletionRequest,+ CreateChatCompletionRequestArgs, ResponseFormat, ResponseFormatJsonSchema,+};+use schemars::{JsonSchema, schema_for};+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),+ name: None,+ });++ let messages: Vec<ChatCompletionRequestMessage> = self+ .messages+ .clone()+ .into_iter()+ .flat_map(Vec::<ChatCompletionRequestMessage>::from)+ .collect();++ all_messages.push(system_message);+ all_messages.extend(messages);+ all_messages+ }+}++impl ChatCompletionRequest {+ /// misnomer this actually uses the -- tools api+ pub fn as_structured_request<S>(+ self,+ stream: bool,+ ) -> anyhow::Result<CreateChatCompletionRequest>+ where+ S: JsonSchema + Metadata + for<'de> Deserialize<'de>,+ {+ let schema = schema_for!(S);+ let json_schema = serde_json::to_value(schema).context("failed to form json_schema")?;+ tracing::debug!(+ "{}",+ serde_json::to_string_pretty(&json_schema).expect("json_string")+ );++ let response_format = ResponseFormat::JsonSchema {+ json_schema: ResponseFormatJsonSchema {+ description: S::description(),+ name: S::name(),+ schema: Some(json_schema),+ strict: Some(true),+ },+ };++ CreateChatCompletionRequestArgs::default()+ .stream(stream)+ .model(self.model.to_string())+ .messages(self.openai_messages())+ .response_format(response_format)+ .build()+ .context("Could not build openai request")+ }+}diff --git a/rust/cloud-storage/ai/src/types/providers/openai/response.rs b/rust/cloud-storage/ai/src/types/providers/openai/response.rsnew file mode 100644index 0000000000..685ad6e2e0--- /dev/null+++ b/rust/cloud-storage/ai/src/types/providers/openai/response.rs@@ -0,0 +1,93 @@+use crate::types::openai::message::order_messages_tool_calls;+use crate::types::{ChatCompletionRequest, response::ChatStreamCompletionResponse};+use anyhow::Context;+use async_openai::types::{+ ChatCompletionRequestMessage, ChatCompletionRequestMessageContentPartText,+ ChatCompletionRequestSystemMessage, ChatCompletionRequestSystemMessageContent,+ ChatCompletionRequestSystemMessageContentPart, CreateChatCompletionRequest,+ CreateChatCompletionRequestArgs, CreateChatCompletionStreamResponse,+ FinishReason as OpenAIFinishReason, ReasoningEffort,+};++/// OPENAI+impl TryFrom<ChatCompletionRequest> for CreateChatCompletionRequest {+ type Error = anyhow::Error;++ 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),+ name: None,+ });++ let messages: Vec<ChatCompletionRequestMessage> = value+ .messages+ .into_iter()+ .flat_map(Vec::<ChatCompletionRequestMessage>::from)+ .collect();+ let messages = order_messages_tool_calls(messages);++ all_messages.push(system_message);+ all_messages.extend(messages);++ let model = value.model.to_string();++ Ok(if value.model.to_string().starts_with("o") {+ CreateChatCompletionRequestArgs::default()+ .model(model)+ .reasoning_effort(ReasoningEffort::High)+ .messages(all_messages)+ .build()?+ } else {+ CreateChatCompletionRequestArgs::default()+ .model(model)+ .reasoning_effort(ReasoningEffort::Medium)+ .messages(all_messages)+ .build()?+ })+ }+}++// Response+impl TryFrom<CreateChatCompletionStreamResponse> for ChatStreamCompletionResponse {+ type Error = anyhow::Error;++ fn try_from(value: CreateChatCompletionStreamResponse) -> anyhow::Result<Self> {+ let choices = value.choices.first().context("no choices");+ let content = if let Ok(choices) = choices {+ let content = choices.delta.content.clone().unwrap_or("".to_string());+ if let Some(finish_reason) = choices.finish_reason {+ match finish_reason {+ OpenAIFinishReason::Stop => {}+ _ => {+ tracing::error!(+ "unexpected finish reason for openai response: {:?}",+ finish_reason,+ );+ }+ }+ }+ content+ } else {+ String::new()+ };+ Ok(ChatStreamCompletionResponse::new_content(+ content,+ value.usage,+ ))+ }+}diff --git a/rust/cloud-storage/anthropic/src/client/mod.rs b/rust/cloud-storage/anthropic/src/client/mod.rsindex 5633fbf65c..a4d8ec17c7 100644--- a/rust/cloud-storage/anthropic/src/client/mod.rs+++ b/rust/cloud-storage/anthropic/src/client/mod.rs@@ -1,6 +1,7 @@pub mod chat;use crate::config::Config;use crate::error::AnthropicError;+use crate::prelude::ApiError;use futures::stream::{Stream, StreamExt};use reqwest::Client as RequestClient;use reqwest_eventsource::{Event, EventSource, RequestBuilderExt};@@ -77,6 +78,19 @@ whereErr(e) => {match e {reqwest_eventsource::Error::StreamEnded => break,+ reqwest_eventsource::Error::InvalidStatusCode(code, response) => {+ let response_err = match response.json::<serde_json::Value>().await {+ Err(e) => AnthropicError::Reqwest(e),+ Ok(json) => match serde_json::from_value::<ApiError>(json) {+ Ok(api_error) => AnthropicError::ApiError {+ api_error,+ status_code: code,+ },+ Err(deserial) => AnthropicError::JsonDeserialize(deserial),+ },+ };+ let _ = tx.send(Err(response_err));+ }other => {let _ = tx.send(Err(AnthropicError::StreamError(other.to_string())));}diff --git a/rust/cloud-storage/anthropic/src/error.rs b/rust/cloud-storage/anthropic/src/error.rsindex 5cadf1f055..5b5f99d0c8 100644--- a/rust/cloud-storage/anthropic/src/error.rs+++ b/rust/cloud-storage/anthropic/src/error.rs@@ -1,5 +1,8 @@+use reqwest::StatusCode;use thiserror::Error;+use crate::prelude::ApiError;+#[derive(Debug, Error)]pub enum AnthropicError {/// An error sent by anthropic@@ -11,6 +14,11 @@ pub enum AnthropicError {/// error from reqwest#[error("http error")]Reqwest(#[from] reqwest::Error),+ #[error("API returned a bad status code")]+ ApiError {+ api_error: ApiError,+ status_code: StatusCode,+ },}pub type Result<T> = std::result::Result<T, AnthropicError>;diff --git a/rust/cloud-storage/anthropic/src/openai/request/conversions.rs b/rust/cloud-storage/anthropic/src/openai/request/conversions.rsindex cc3560de35..c4039b8836 100644--- a/rust/cloud-storage/anthropic/src/openai/request/conversions.rs+++ b/rust/cloud-storage/anthropic/src/openai/request/conversions.rs@@ -25,12 +25,14 @@ pub enum MessageConversionError {FunctionMessage(ChatCompletionRequestFunctionMessage),}+const MAX_OUTPUT_TOKENS: u32 = 32_000;+impl From<CreateChatCompletionRequest> for request::CreateMessageRequestBody {fn from(msg: CreateChatCompletionRequest) -> Self {let mut request = Self {max_tokens: msg.max_completion_tokens.unwrap_or(#[allow(deprecated)]- msg.max_tokens.unwrap_or(32_000),+ msg.max_tokens.unwrap_or(MAX_OUTPUT_TOKENS),),..Default::default()};diff --git a/rust/cloud-storage/anthropic/src/openai/stream_response.rs b/rust/cloud-storage/anthropic/src/openai/stream_response.rsindex 6bf3e523f9..d86aa80c64 100644--- a/rust/cloud-storage/anthropic/src/openai/stream_response.rs+++ b/rust/cloud-storage/anthropic/src/openai/stream_response.rs@@ -121,6 +121,15 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletionAnthropicError::JsonDeserialize(e) => OpenAIError::JSONDeserialize(e),AnthropicError::Reqwest(e) => OpenAIError::Reqwest(e),AnthropicError::StreamError(e) => OpenAIError::StreamError(e),+ AnthropicError::ApiError { status_code, api_error } => {+ OpenAIError::ApiError(ApiError {+ message: api_error.error.message,+ r#type: Some(api_error.r#type),+ param: None,+ code: Some(status_code.to_string())+ })+ }+})} else {match part.unwrap() {diff --git a/rust/cloud-storage/anthropic/src/types/response.rs b/rust/cloud-storage/anthropic/src/types/response.rsindex 15587c2ee2..a9b1ca6fb1 100644--- a/rust/cloud-storage/anthropic/src/types/response.rs+++ b/rust/cloud-storage/anthropic/src/types/response.rs@@ -66,6 +66,19 @@ pub enum StopReason {Refusal,}+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]+pub struct ApiError {+ pub r#type: String,+ pub request_id: String,+ pub error: Error,+}++#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]+pub struct Error {+ pub r#type: String,+ pub message: String,+}+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]pub struct Usage {#[serde(skip_serializing_if = "Option::is_none")]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.rsindex 12c2de3cfc..b6c6f85d3e 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@@ -5,7 +5,7 @@ use crate::api::ws::connection::{MESSAGE_ABORT_MAP, add_partial_message_part, clear_partial_message, register_partial_message,ws_send,};-use crate::core::model::ONE_MODEL;+use crate::core::model::FALLBACK_MODEL;use crate::model::chats::ChatResponse;use crate::model::ws::{StreamError, StreamWebSocketError};use crate::{@@ -102,7 +102,7 @@ pub async fn stream_chat_response(connection_id: &str,stream_id: &str,jwt_token: &str,-) -> Result<StreamChatResponse> {+) -> Result<StreamChatResponse, ai::types::AiError> {if MESSAGE_ABORT_MAP.contains_key(stream_id) {MESSAGE_ABORT_MAP.remove(stream_id);// No database cleanup needed since we don't create partial messages until disconnect@@ -129,8 +129,7 @@ pub async fn stream_chat_response(let now = std::time::Instant::now();let mut stream = chat.send_message(request, request_context, user_id.to_owned())- .await- .context("failed to send message to AI client")?;+ .await?;// Register potential partial message with connection for disconnect-based savingregister_partial_message(connection_id, message_id, chat_id, Some(model.to_string()));@@ -139,11 +138,12 @@ pub async fn stream_chat_response(let mut usage_reqs = vec![];let mut is_first_token = false;while let Some(response) = stream.next().await {+ tracing::trace!("{:#?}", response);if !is_first_token {is_first_token = true;log::log_timing(log::LatencyMetric::TimeToFirstToken, model, now.elapsed());}- let response_chunk = response.context("failed to read stream chunk")?;+ let response_chunk = response?;// Abort streaming for a message if it has been stoppedif MESSAGE_ABORT_MAP.contains_key(stream_id) {MESSAGE_ABORT_MAP.remove(stream_id);@@ -330,7 +330,7 @@ pub async fn handle_send_chat_message(}})?;let is_first_message = chat.messages.is_empty();- let model = ONE_MODEL;+ let model = FALLBACK_MODEL;let user_message_id =store_incoming_message(ctx.clone(), user_id, &chat, model, &incoming_message)@@ -369,8 +369,13 @@ pub async fn handle_send_chat_message(.await.map_err(|err| {tracing::error!(error=?err, "failed to stream chat response");- StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),+ match err {+ ai::types::AiError::ContextWindowExceeded => StreamError::ModelContextOverflow {+ stream_id: incoming_message.stream_id.clone(),+ },+ ai::types::AiError::Generic(_) => StreamError::InternalError {+ stream_id: incoming_message.stream_id.clone(),+ },}})?;diff --git a/rust/cloud-storage/document_cognition_service/src/core/model.rs b/rust/cloud-storage/document_cognition_service/src/core/model.rsindex a4ad17ecbd..9c99db5f4e 100644--- a/rust/cloud-storage/document_cognition_service/src/core/model.rs+++ b/rust/cloud-storage/document_cognition_service/src/core/model.rs@@ -2,8 +2,6 @@ use ai::types::Model;pub static CHAT_MODELS: &[Model] = &[Model::Claude45Haiku, Model::Claude45Sonnet];-pub static ONE_MODEL: Model = Model::Claude45Haiku;-pub static COMPLETION_MODEL: Model = Model::OpenAiGpt41;pub static COMPLETION_CONTEXT_WINDOW: i32 = 80000;pub static FALLBACK_MODEL: Model = Model::Claude45Haiku;diff --git a/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rsindex 30f85101ab..506577bada 100644--- a/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs@@ -267,7 +267,7 @@ pub enum StreamError {ProviderError { stream_id: String, model: Model },#[error("model context overflow")]- ModelContextOverflow { stream_id: String, model: Model },+ ModelContextOverflow { stream_id: String },#[error("internal error")]InternalError { stream_id: String },@@ -296,10 +296,9 @@ impl StreamWebSocketError {StreamWebSocketError::StreamError(StreamError::ProviderError { stream_id, .. }) => {stream_id}- StreamWebSocketError::StreamError(StreamError::ModelContextOverflow {- stream_id,- ..- }) => stream_id,+ StreamWebSocketError::StreamError(StreamError::ModelContextOverflow { stream_id }) => {+ stream_id+ }StreamWebSocketError::StreamError(StreamError::InternalError { stream_id, .. }) => {stream_id}diff --git a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rsindex 6162410f54..1e8bfcb6fe 100644--- a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs@@ -1,16 +1,14 @@// biohazarduse crate::api::context::ApiContext;-use crate::core::model::{CHAT_MODELS, FALLBACK_MODEL};+use crate::core::model::FALLBACK_MODEL;use crate::model::chats::ChatResponse;use ai::model_selection::ModelSelection;-use ai::{model_selection::select_model, types::Model};use anyhow::Context;use macro_db_client::dcs::get_chat::{get_chat_db, get_messages, get_web_citations, raw_attachments,};use macro_db_client::dcs::get_document_name_and_type::get_document_name_and_type;use model::chat::{AttachmentMetadata, AttachmentType, ChatAttachmentWithName};-use std::str::FromStr;use unfurl_service::GetUnfurlResponse;#[tracing::instrument(err, skip(ctx))]@@ -92,15 +90,13 @@ pub async fn get_chat(.await.context("Failed to get messages")?;- let model = chat- .model- .map(|m| Model::from_str(&m).unwrap_or(FALLBACK_MODEL));+ let model = Some(FALLBACK_MODEL);- let model_selection = select_model(None, chat.token_count.unwrap_or(0), CHAT_MODELS.to_vec())- .unwrap_or_else(|_| ModelSelection {- available_models: vec![],- new_model: None,- });+ // relic of model selection+ let model_selection = ModelSelection {+ available_models: vec![FALLBACK_MODEL],+ new_model: None,+ };let web_citations = get_web_citations(&ctx.db, chat_id).await