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
fix(ai): tool error handling (#2671)
Eric Hayes80ea6e6f0529
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rsindex 84e9d9b406..145e28ee4f 100644--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs@@ -154,8 +154,9 @@ wherestream_parts: Vec<PartOrExt<I::ResponseExtension>>,request_context: RequestContext,) -> ProcessedStream {- let mut messages: Vec<ChatCompletionRequestMessage> = vec![];- let mut tool_stream_parts: Vec<ToolResponse> = vec![];+ let mut new_messages: Vec<ChatCompletionRequestMessage> = vec![];+ // yielded to consumer+ let mut tool_responses: Vec<ToolResponse> = vec![];// Current assistant segment being builtlet mut content = String::new();@@ -183,14 +184,14 @@ whereStreamPart::ToolResponse(ToolResponse::Json { id, json, .. }) => {// Server-side tool response - flush current assistant and start new segmentif !content.is_empty() || !tool_calls.is_empty() {- messages.push(+ new_messages.push(self.make_assistant_message(&mut content, &mut tool_calls),);- messages.append(&mut pending_tool_messages);+ new_messages.append(&mut pending_tool_messages);}let content_text = serde_json::to_string_pretty(&json).unwrap_or_else(|_| "internal error parsing".into());- messages.push(ChatCompletionRequestMessage::Tool(+ new_messages.push(ChatCompletionRequestMessage::Tool(ChatCompletionRequestToolMessage {content: async_openai::types::ChatCompletionRequestToolMessageContent::Text(content_text,@@ -216,7 +217,7 @@ where},});- let tool_response = match self+ let tool_response_text = match self.toolset.try_tool_call(self.context.clone(),@@ -226,30 +227,34 @@ where).await{+ // found tool and call successOk(ToolResult::Ok(output)) => {- let content_text = serde_json::to_string_pretty(&output)+ let json_string = serde_json::to_string_pretty(&output).unwrap_or_else(|_| {"internal error formatting response".to_string()});- tool_stream_parts.push(ToolResponse::Json {+ tool_responses.push(ToolResponse::Json {id: call.id.clone(),json: output,name: call.name.clone(),});- content_text+ json_string}+ // found tool and call failOk(ToolResult::Err(fail)) => {- tool_stream_parts.push(ToolResponse::Err {+ tracing::error!(error=?fail, "tool execution error");+ tool_responses.push(ToolResponse::Err {id: call.id.clone(),description: fail.description.clone(),name: call.name.clone(),});fail.description}+ // tool call not found | malformed jsonErr(err) => {tracing::error!(error=?err, "error calling tool");let desc = format!("Error calling tool: {}", err);- tool_stream_parts.push(ToolResponse::Err {+ tool_responses.push(ToolResponse::Err {id: call.id.clone(),description: desc.clone(),name: call.name.clone(),@@ -258,10 +263,11 @@ where}};+ // response message in message chainpending_tool_messages.push(ChatCompletionRequestMessage::Tool(ChatCompletionRequestToolMessage {content: async_openai::types::ChatCompletionRequestToolMessageContent::Text(- tool_response,+ tool_response_text,),tool_call_id: call.id,},@@ -274,12 +280,12 @@ where}// Flush remaining assistant content- messages.push(self.make_assistant_message(&mut content, &mut tool_calls));- messages.append(&mut pending_tool_messages);+ new_messages.push(self.make_assistant_message(&mut content, &mut tool_calls));+ new_messages.append(&mut pending_tool_messages);ProcessedStream {- new_messages: messages,- tool_responses: tool_stream_parts,+ new_messages,+ tool_responses,}}diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rsindex 9dc3855f3a..32c1ce9cfe 100644--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs@@ -602,7 +602,7 @@ mod tests {ChatCompletionRequestToolMessage {tool_call_id: tool_call_id.clone(),content: ChatCompletionRequestToolMessageContent::Text(- json!({"type": "error", "description": "Tool execution failed"}).to_string(),+ "Tool execution failed".into(),),},)];@@ -625,6 +625,7 @@ mod tests {assert_eq!(id, &tool_call_id);assert_eq!(description, "Tool execution failed");} else {+ eprintln!("{:#?}", parts[0]);panic!("Expected tool error part");}} else {diff --git a/rust/cloud-storage/ai/src/types/providers/openai/message.rs b/rust/cloud-storage/ai/src/types/providers/openai/message.rsindex 640121ed59..88d560fd1f 100644--- a/rust/cloud-storage/ai/src/types/providers/openai/message.rs+++ b/rust/cloud-storage/ai/src/types/providers/openai/message.rs@@ -11,18 +11,10 @@ use async_openai::types::{use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, ChatMessages, ImageData, Role,};-use serde::Serialize;use std::collections::HashMap;const IMAGE_PROCESS_QUALITY: Option<ImageDetail> = Some(ImageDetail::High);-#[derive(Serialize)]-struct ToolResponseParseError {- error: String,- raw_response: String,- parse_error: String,-}-impl From<ImageData> for ImageUrl {fn from(value: ImageData) -> Self {match value {@@ -176,23 +168,17 @@ impl From<ChatMessage> for Vec<ChatCompletionRequestMessage> {AssistantMessagePart::ToolCallErr {description, id, ..} => {- // If we have accumulated text, create a text message firstflush_pending(&mut messages,&mut pending_text,&mut pending_tool_calls,);- // Create a separate tool error response message with error markermessages.push(ChatCompletionRequestMessage::Tool(ChatCompletionRequestToolMessage {tool_call_id: id.clone(),content: ChatCompletionRequestToolMessageContent::Text(- serde_json::json!({- "type": "error",- "description": description- })- .to_string(),+ description,),},));@@ -366,25 +352,6 @@ pub fn convert_message(}};- let response_json = match serde_json::from_str::<serde_json::Value>(&response_text) {- Ok(json) => json,- Err(e) => {- tracing::error!(- err=?e,- response_text=%response_text,- tool_call_id=%tool_msg.tool_call_id,- "Failed to parse tool response as JSON, creating error response"- );- // Create structured error response instead of empty JSON- let error_response = ToolResponseParseError {- error: "Invalid JSON response".to_string(),- raw_response: response_text,- parse_error: e.to_string(),- };- serde_json::to_value(error_response).unwrap_or(serde_json::Value::Null)- }- };-// Use the mapping to recover the original tool namelet tool_name = tool_call_id_name_mapping.and_then(|mapping| mapping.get(&tool_msg.tool_call_id).cloned())@@ -397,35 +364,17 @@ pub fn convert_message(tool_msg.tool_call_id.clone()});- // Check if this is an error response based on the structure- let assistant_part = if let Some(obj) = response_json.as_object() {- if obj.get("type").and_then(|v| v.as_str()) == Some("error") {- if let Some(description) = obj.get("description").and_then(|v| v.as_str()) {- AssistantMessagePart::ToolCallErr {- name: tool_name,- description: description.to_string(),- id: tool_msg.tool_call_id,- }- } else {- AssistantMessagePart::ToolCallResponseJson {- name: tool_name,- json: response_json,- id: tool_msg.tool_call_id,- }- }- } else {- AssistantMessagePart::ToolCallResponseJson {- name: tool_name,- json: response_json,- id: tool_msg.tool_call_id,- }- }- } else {- AssistantMessagePart::ToolCallResponseJson {+ let assistant_part = match serde_json::from_str::<serde_json::Value>(&response_text) {+ Ok(json) => AssistantMessagePart::ToolCallResponseJson {name: tool_name,- json: response_json,+ json,id: tool_msg.tool_call_id,- }+ },+ Err(_) => AssistantMessagePart::ToolCallErr {+ name: tool_name,+ description: response_text,+ id: tool_msg.tool_call_id,+ },};ChatMessage {