Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: anthropic no response (#2189)

Eric Hayes95743c0afb95
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 8f47a5b849..abb048550a 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
@@ -1,4 +1,3 @@
-use super::chained::Chained;
use super::chat::Chat;
use crate::tool::types::AsyncToolSet;
use crate::types::AnthropicClient;
@@ -47,12 +46,4 @@ where
self.context.clone(),
)
}
-
- pub fn chained(&self) -> Chained<I, T> {
- Chained::new(
- self.client.clone(),
- self.toolset.clone(),
- self.context.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
deleted file mode 100644
index 81d6ab16d0..0000000000
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chained.rs
+++ /dev/null
@@ -1,441 +0,0 @@
-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, RequestContext, StreamPart, ToolCall, ToolResult,
-};
-use crate::tool::types::{ChatCompletionStream, ToolResponse};
-
-use crate::types::openai::message::convert_message;
-use crate::types::traits::ExtendedOpenAIStream;
-use crate::types::{
- ChatCompletionRequest, ChatMessage, ChatMessages, MessageBuilder, Result, SystemPrompt,
-};
-use crate::types::{ExtendedClient, ExtendedOpenAIStreamItem};
-use async_openai::types::{
- ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,
- ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,
- ChatCompletionRequestToolMessage, ChatCompletionStreamOptions, ChatCompletionTool,
- ChatCompletionToolType, CreateChatCompletionRequest, FinishReason, FunctionCall,
- FunctionObject,
-};
-use async_stream::stream;
-use futures::stream::StreamExt;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-use std::sync::Arc;
-
-struct ProcessedStream {
- pub new_messages: Vec<ChatCompletionRequestMessage>,
- pub tool_responses: Vec<ToolResponse>,
-}
-
-#[derive(Debug, JsonSchema, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct ChainedTool {
- #[schemars(description = "name of tool to use")]
- pub tool_name: String,
- #[schemars(
- description = "instructions to use tool. Include all needed context including ids, names, and user instructiomns"
- )]
- pub instructions: String,
-}
-
-// The chained API is identical to the chat API
-///
-/// This loop doesn't send tool JSON schema to the selected model.
-/// Instead this client sends (name, description) data of each tool,
-/// then gives the primary model a tool to call a tool with
-/// (name, instructions). This tool call is then used to send a single
-/// tool to a secondary model that makes the tool call.
-///
-/// This is done transparently so the calls to the `ChainedTool` are not
-/// persisted to the database or presented to the frontend. This is
-/// intended to be a drop-in replacement for the `Chat` client
-impl ChainedTool {
- pub fn as_openai_tool() -> ChatCompletionTool {
- let schema = generate_tool_input_schema!(ChainedTool);
- ChatCompletionTool {
- r#type: ChatCompletionToolType::Function,
- function: FunctionObject {
- name: "chainedTool".into(),
- description: Some(
- "Call a tool by naming it and describing how it should be called".into(),
- ),
- strict: Some(true),
- parameters: Some(schema.to_value()),
- },
- }
- }
-}
-
-fn build_tool_prompt<T>(toolset: &AsyncToolSet<T>) -> String {
- toolset
- .tools
- .values()
- .map(|v| {
- format!(
- r#"[CHAINED TOOL]
-name: {},
-description: {}
-[END CHAINED TOOL]"#,
- v.name, v.description
- )
- })
- .collect::<Vec<_>>()
- .join("\n")
-}
-
-pub struct Chained<I, T>
-where
- I: ExtendedClient + Send + Sync + Clone,
- T: Clone + Send + Sync + 'static,
-{
- inner: I,
- toolset: Arc<AsyncToolSet<T>>,
- request: CreateChatCompletionRequest,
- messages: Vec<ChatCompletionRequestMessage>,
- context: T,
- initial_message_count: usize,
- tool_call_id_name_mapping: HashMap<String, String>, // tool_call_id -> tool_name
- tool_call_count: usize,
-}
-
-impl<I, T> Chained<I, T>
-where
- I: ExtendedClient + Send + Sync + Clone,
- T: Clone + Send + Sync,
-{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T>>, context: T) -> Chained<I, T> {
- Self {
- inner: client,
- toolset,
- messages: vec![],
- context,
- request: CreateChatCompletionRequest::default(),
- initial_message_count: 0,
- tool_call_id_name_mapping: HashMap::new(),
- tool_call_count: 0,
- }
- }
-
- pub async fn send_message(
- &mut self,
- mut request: ChatCompletionRequest,
- request_context: RequestContext,
- ) -> Result<ChatCompletionStream<'_>> {
- // tell the primary model how all the tools will work
- request
- .system_prompt
- .instructions
- .push_str(&build_tool_prompt(&self.toolset));
-
- self.request = request.try_into()?;
- self.messages = self.request.messages.clone();
- self.initial_message_count = self.messages.len();
-
- self.make_chat_completion_stream(request_context).await
- }
-
- pub fn get_new_conversation_messages(&self) -> Vec<ChatMessage> {
- let messages: ChatMessages = self
- .messages
- .iter()
- .skip(self.initial_message_count)
- .map(|msg| convert_message(msg.clone(), Some(&self.tool_call_id_name_mapping)))
- .collect::<Vec<_>>()
- .into();
- messages.0
- }
-
- async fn route_chained_calls(
- toolset: &Arc<AsyncToolSet<T>>,
- 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"))
- .map_err(anyhow::Error::from)?;
-
- let selected_tool = toolset
- .tools
- .get(&chained.tool_name)
- .ok_or(anyhow::anyhow!("AI returned an uknown tool"))
- .inspect_err(|err| tracing::warn!(err=?err))?;
-
- tool_completion(
- ChatCompletionRequest {
- model: TOOL_GENERATOR,
- messages: vec![
- MessageBuilder::new()
- .user()
- .content(chained.instructions.clone())
- .build(),
- ],
- system_prompt: SystemPrompt {
- attachments: Default::default(),
- instructions:
- "Use the tool provided in context following the user instructions".into(),
- },
- },
- selected_tool,
- )
- .await
- }
-
- async fn make_chat_completion_stream(
- &mut self,
- request_context: RequestContext,
- ) -> Result<ChatCompletionStream<'_>> {
- let item_stream = stream!({
- let mut stream_parts = vec![];
- for _ in 0..MAX_RECURSIONS {
- let stream = match self.make_openai_chat_completion_stream().await {
- Ok(stream) => stream,
- Err(err) => {
- yield Err(err);
- break;
- }
- };
-
- {
- let mut stream = Self::map_stream(&self.inner, stream);
-
- // consume stream
- // accumulate to stream_parts
- while let Some(item) = stream.next().await {
- if item.is_err() {
- yield item;
- break;
- }
-
- let stream_part = match item.unwrap() {
- StreamPart::ToolCall(call) => StreamPart::ToolCall(
- Self::route_chained_calls(&self.toolset, call).await?,
- ),
- other => other,
- };
-
- yield Ok(stream_part.clone());
- stream_parts.push(stream_part);
- }
- }
- // call tools, aggregate response to a new request
- let mut processed = self
- .process_stream_parts(stream_parts, request_context.clone())
- .await;
-
- for response in &processed.tool_responses {
- yield Ok(StreamPart::ToolResponse(response.clone()));
- }
-
- self.messages.append(&mut processed.new_messages);
- // if there are no tool calls, then done
- if processed.tool_responses.is_empty() {
- break;
- }
- stream_parts = vec![];
- }
- });
- Ok(Box::pin(item_stream))
- }
-
- async fn process_stream_parts(
- &mut self,
- stream_parts: Vec<StreamPart>,
- request_context: RequestContext,
- ) -> ProcessedStream {
- // list of all tool calls
- let mut tool_calls = vec![];
- // list of all tool responses as openai items
- let mut tool_responses = vec![];
- // aggregated response string
- let mut response = String::new();
- // list of tool responses as stream parts (send these to frontend)
- let mut tool_stream_parts = vec![];
- for item in stream_parts {
- match item {
- StreamPart::ToolCall(call) => {
- // Store the tool call ID -> name mapping for later use in message conversion
- self.tool_call_count += 1;
- // Gemini uses tool call ids that are incompatible with openai
- let tool_call_id = format!("toolu_{}", self.tool_call_count);
- self.tool_call_id_name_mapping
- .insert(tool_call_id.clone(), call.name.clone());
-
- if let Ok(response) = self
- .toolset
- .try_tool_call(
- self.context.clone(),
- request_context.clone(),
- &call.name,
- &call.json,
- )
- .await
- .inspect_err(|err| eprintln!("error: {:?}", err))
- {
- tool_calls.push(ChatCompletionMessageToolCall {
- id: tool_call_id.clone(),
- r#type: async_openai::types::ChatCompletionToolType::Function,
- function: FunctionCall {
- arguments: call.json.to_string(),
- name: call.name.clone(),
- },
- });
- if let ToolResult::Ok(tool_output) = response {
- let content_text = serde_json::to_string_pretty(&tool_output)
- .unwrap_or_else(|_| {
- "internal error formatting response".to_string()
- });
- tool_stream_parts.push(ToolResponse::Json {
- id: tool_call_id.clone(),
- json: tool_output,
- name: call.name.clone(),
- });
- let content =
- async_openai::types::ChatCompletionRequestToolMessageContent::Text(
- content_text,
- );
- tool_responses.push(ChatCompletionRequestMessage::Tool(
- ChatCompletionRequestToolMessage {
- content,
- tool_call_id: tool_call_id.clone(),
- },
- ));
- } else {
- let fail = response.unwrap_err();
- tool_stream_parts.push(ToolResponse::Err {
- id: tool_call_id.clone(),
- description: fail.description.clone(),
- name: call.name.clone(),
- });
- tool_responses.push(ChatCompletionRequestMessage::Tool(
- ChatCompletionRequestToolMessage {
- content: async_openai::types::ChatCompletionRequestToolMessageContent::Text(
- fail.description
- ),
- tool_call_id: tool_call_id.clone()
- },
- ));
- }
- }
- }
- StreamPart::Content(text) => response.push_str(text.as_str()),
- StreamPart::Usage { .. } => (),
- StreamPart::ToolResponse(_) => (),
- };
- }
-
- let assistant_response =
- ChatCompletionRequestMessage::Assistant(ChatCompletionRequestAssistantMessage {
- content: if response.is_empty() {
- None
- } else {
- Some(ChatCompletionRequestAssistantMessageContent::Text(response))
- },
- tool_calls: if tool_calls.is_empty() {
- None
- } else {
- Some(tool_calls)
- },
- ..Default::default()
- });
- let mut messages = vec![assistant_response];
- messages.append(&mut tool_responses);
- ProcessedStream {
- new_messages: messages,
- tool_responses: tool_stream_parts,
- }
- }
-
- fn map_stream<'a>(
- client: &'a I,
- mut stream: ExtendedOpenAIStream<I::ResponseExtension>,
- ) -> ChatCompletionStream<'a> {
- Box::pin(stream!({
- let mut tool_calls: HashMap<u32, PartialToolCall> = HashMap::new();
- while let Some(part) = stream.next().await {
- match part {
- Ok(ExtendedOpenAIStreamItem::Response(part)) => {
- if let Some(usage) = &part.usage {
- yield Ok(StreamPart::Usage(usage.clone().into()))
- }
- let first = part.choices.first();
- if first.is_none() {
- continue;
- }
- let first = first.unwrap();
- if let Some(content) = &first.delta.content {
- yield Ok(StreamPart::Content(content.clone()));
- }
-
- if let Some(calls) = &first.delta.tool_calls {
- for call in calls {
- if let Some(function) = &call.function {
- tool_calls
- .entry(call.index)
- .and_modify(|partial| {
- if let Some(n) = &function.name {
- partial.name = format!("{}{}", partial.name, n);
- }
- if let Some(a) = &function.arguments.clone() {
- partial.json = format!("{}{}", partial.json, a);
- }
- if let Some(id) = &call.id {
- partial.id = id.clone();
- }
- })
- .or_insert_with(|| {
- let mut partial = PartialToolCall::default();
- if let Some(n) = function.name.clone() {
- partial.name = n;
- }
- if let Some(a) = function.arguments.clone() {
- partial.json = a;
- }
- if let Some(id) = &call.id {
- partial.id = id.clone();
- }
- partial
- });
- }
- }
- }
- if let Some(FinishReason::ToolCalls) = first.finish_reason {
- for call in tool_calls.into_values() {
- if let Ok(call) = ToolCall::try_from(call) {
- yield Ok(StreamPart::ToolCall(call));
- }
- }
- tool_calls = HashMap::new();
- }
- }
- Ok(ExtendedOpenAIStreamItem::Extension(ext)) => {
- // Handle provider-specific extension items (Anthropic server tools)
- if let Some(stream_part) = client.handle_extension_item(ext) {
- yield Ok(stream_part);
- }
- }
- Err(error) => yield Err(error.into()),
- }
- }
- }))
- }
-
- async fn make_openai_chat_completion_stream(
- &mut self,
- ) -> Result<ExtendedOpenAIStream<I::ResponseExtension>> {
- self.request.messages = self.messages.clone();
- // don't send the tools
- self.request.tools = Some(vec![ChainedTool::as_openai_tool()]);
- self.request.stream = Some(true);
- self.request.stream_options = Some(ChatCompletionStreamOptions {
- include_usage: true,
- });
-
- tracing::trace!("{:#?}", self.request);
-
- self.inner.chat_stream(self.request.clone()).await
- }
-}
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.rs
new file mode 100644
index 0000000000..84e9d9b406
--- /dev/null
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs
@@ -0,0 +1,467 @@
+use super::MAX_RECURSIONS;
+use crate::openai_toolset::OpenAIToolSetExt;
+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};
+use crate::types::{ChatCompletionRequest, ChatMessage, ChatMessages};
+use crate::types::{ExtendedClient, Result};
+use async_openai::types::{
+ ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,
+ ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,
+ ChatCompletionRequestToolMessage, ChatCompletionStreamOptions, CreateChatCompletionRequest,
+ FinishReason, FunctionCall,
+};
+use async_stream::stream;
+use futures::stream::StreamExt;
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+
+struct ProcessedStream {
+ pub new_messages: Vec<ChatCompletionRequestMessage>,
+ pub tool_responses: Vec<ToolResponse>,
+}
+
+pub struct Chat<I, T>
+where
+ I: ExtendedClient + Send + Sync,
+ T: Clone + Send + Sync + 'static,
+{
+ client: I,
+ toolset: Arc<AsyncToolSet<T>>,
+ request: CreateChatCompletionRequest,
+ pub(crate) messages: Vec<ChatCompletionRequestMessage>,
+ context: T,
+ pub(crate) initial_message_count: usize,
+ pub(crate) tool_call_id_name_mapping: HashMap<String, String>, // tool_call_id -> tool_name
+ user_id: String,
+}
+
+impl<I, T> Chat<I, T>
+where
+ I: ExtendedClient + Send + Sync,
+ T: Clone + Send + Sync,
+{
+ pub fn new(client: I, toolset: Arc<AsyncToolSet<T>>, context: T) -> Chat<I, T> {
+ Chat {
+ client,
+ toolset,
+ messages: vec![],
+ context,
+ request: CreateChatCompletionRequest::default(),
+ initial_message_count: 0,
+ tool_call_id_name_mapping: HashMap::new(),
+ user_id: "Uninitialized".into(),
+ }
+ }
+
+ #[tracing::instrument(skip(self, request_context), err)]
+ pub async fn send_message(
+ &mut self,
+ request: ChatCompletionRequest,
+ request_context: RequestContext,
+ user_id: String,
+ ) -> Result<ChatCompletionStream<'_>> {
+ self.request = request.try_into()?;
+ self.messages = self.request.messages.clone();
+ self.initial_message_count = self.messages.len();
+ self.user_id = user_id;
+
+ self.make_chat_completion_stream(request_context).await
+ }
+
+ pub fn get_new_conversation_messages(&self) -> Vec<ChatMessage> {
+ let messages: ChatMessages = self
+ .messages
+ .iter()
+ .skip(self.initial_message_count)
+ .map(|msg| convert_message(msg.clone(), Some(&self.tool_call_id_name_mapping)))
+ .collect::<Vec<_>>()
+ .into();
+ messages.0
+ }
+}
+
+impl<I, T> Chat<I, T>
+where
+ I: ExtendedClient + Send + Sync,
+ T: Clone + Send + Sync,
+{
+ #[tracing::instrument(err, skip_all)]
+ async fn make_chat_completion_stream(
+ &mut self,
+ request_context: RequestContext,
+ ) -> Result<ChatCompletionStream<'_>> {
+ let item_stream = stream!({
+ let mut stream_parts = vec![];
+ 'outer: for _ in 0..MAX_RECURSIONS {
+ let stream = match self.make_openai_chat_completion_stream().await {
+ Ok(stream) => stream,
+ Err(err) => {
+ yield Err(err);
+ break;
+ }
+ };
+ {
+ let mut stream = Self::map_stream(stream);
+ // consume stream
+ // accumulate to stream_parts
+ while let Some(item) = stream.next().await {
+ if let Err(e) = item {
+ yield Err(e);
+ break 'outer;
+ }
+
+ let part_or_ext = item.unwrap();
+ match part_or_ext {
+ ref part @ PartOrExt::Part(ref p) => {
+ yield Ok(p.to_owned());
+ stream_parts.push(part.to_owned());
+ }
+ ref part @ PartOrExt::Ext(ref e) => {
+ if let Some(p) = self.client.handle_extension_item(e.to_owned()) {
+ yield Ok(p);
+ }
+ stream_parts.push(part.to_owned());
+ }
+ }
+ }
+ }
+ // call tools, aggregate response to a new request
+ let mut processed = self
+ .process_stream_parts(stream_parts, request_context.clone())
+ .await;
+
+ for response in &processed.tool_responses {
+ yield Ok(StreamPart::ToolResponse(response.clone()));
+ }
+
+ self.messages.append(&mut processed.new_messages);
+ // if there are no tool calls, then done
+ if processed.tool_responses.is_empty() {
+ break;
+ }
+ stream_parts = vec![];
+ }
+ });
+ Ok(Box::pin(item_stream))
+ }
+
+ async fn process_stream_parts(
+ &mut self,
+ stream_parts: Vec<PartOrExt<I::ResponseExtension>>,
+ request_context: RequestContext,
+ ) -> ProcessedStream {
+ let mut messages: Vec<ChatCompletionRequestMessage> = vec![];
+ let mut tool_stream_parts: Vec<ToolResponse> = vec![];
+
+ // Current assistant segment being built
+ let mut content = String::new();
+ let mut tool_calls: Vec<ChatCompletionMessageToolCall> = vec![];
+ let mut pending_tool_messages: Vec<ChatCompletionRequestMessage> = vec![];
+
+ for item in stream_parts {
+ match item {
+ PartOrExt::Ext(ext) => {
+ if let Some(stream_part) = self.client.handle_extension_item(ext) {
+ match stream_part {
+ StreamPart::ToolCall(call) => {
+ self.tool_call_id_name_mapping
+ .insert(call.id.clone(), call.name.clone());
+ tool_calls.push(ChatCompletionMessageToolCall {
+ id: call.id.clone(),
+ r#type: async_openai::types::ChatCompletionToolType::Function,
+ function: FunctionCall {
+ arguments: call.json.to_string(),
+ name: call.name.clone(),
+ },
+ });
+ }
+ StreamPart::Content(text) => content.push_str(text.as_str()),
+ StreamPart::ToolResponse(ToolResponse::Json { id, json, .. }) => {
+ // Server-side tool response - flush current assistant and start new segment
+ if !content.is_empty() || !tool_calls.is_empty() {
+ messages.push(
+ self.make_assistant_message(&mut content, &mut tool_calls),
+ );
+ 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(
+ ChatCompletionRequestToolMessage {
+ content: async_openai::types::ChatCompletionRequestToolMessageContent::Text(
+ content_text,
+ ),
+ tool_call_id: id,
+ },
+ ));
+ }
+ StreamPart::Usage { .. } | StreamPart::ToolResponse(_) => {}
+ }
+ }
+ }
+ PartOrExt::Part(part) => match part {
+ StreamPart::ToolCall(call) => {
+ self.tool_call_id_name_mapping
+ .insert(call.id.clone(), call.name.clone());
+ tool_calls.push(ChatCompletionMessageToolCall {
+ id: call.id.clone(),
+ r#type: async_openai::types::ChatCompletionToolType::Function,
+ function: FunctionCall {
+ arguments: call.json.to_string(),
+ name: call.name.clone(),
+ },
+ });
+
+ let tool_response = match self
+ .toolset
+ .try_tool_call(
+ self.context.clone(),
+ request_context.clone(),
+ &call.name,
+ &call.json,
+ )
+ .await
+ {
+ Ok(ToolResult::Ok(output)) => {
+ let content_text = serde_json::to_string_pretty(&output)
+ .unwrap_or_else(|_| {
+ "internal error formatting response".to_string()
+ });
+ tool_stream_parts.push(ToolResponse::Json {
+ id: call.id.clone(),
+ json: output,
+ name: call.name.clone(),
+ });
+ content_text
+ }
+ Ok(ToolResult::Err(fail)) => {
+ tool_stream_parts.push(ToolResponse::Err {
+ id: call.id.clone(),
+ description: fail.description.clone(),
+ name: call.name.clone(),
+ });
+ fail.description
+ }
+ Err(err) => {
+ tracing::error!(error=?err, "error calling tool");
+ let desc = format!("Error calling tool: {}", err);
+ tool_stream_parts.push(ToolResponse::Err {
+ id: call.id.clone(),
+ description: desc.clone(),
+ name: call.name.clone(),
+ });
+ desc
+ }
+ };
+
+ pending_tool_messages.push(ChatCompletionRequestMessage::Tool(
+ ChatCompletionRequestToolMessage {
+ content: async_openai::types::ChatCompletionRequestToolMessageContent::Text(
+ tool_response,
+ ),
+ tool_call_id: call.id,
+ },
+ ));
+ }
+ StreamPart::Content(text) => content.push_str(text.as_str()),
+ StreamPart::Usage { .. } | StreamPart::ToolResponse(_) => {}
+ },
+ }
+ }
+
+ // Flush remaining assistant content
+ messages.push(self.make_assistant_message(&mut content, &mut tool_calls));
+ messages.append(&mut pending_tool_messages);
+
+ ProcessedStream {
+ new_messages: messages,
+ tool_responses: tool_stream_parts,
+ }
+ }
+
+ fn make_assistant_message(
+ &self,
+ content: &mut String,
+ tool_calls: &mut Vec<ChatCompletionMessageToolCall>,
+ ) -> ChatCompletionRequestMessage {
+ ChatCompletionRequestMessage::Assistant(ChatCompletionRequestAssistantMessage {
+ content: if content.is_empty() {
+ None
+ } else {
+ Some(ChatCompletionRequestAssistantMessageContent::Text(
+ std::mem::take(content),
+ ))
+ },
+ tool_calls: if tool_calls.is_empty() {
+ None
+ } else {
+ Some(std::mem::take(tool_calls))
+ },
+ ..Default::default()
+ })
+ }
+
+ fn map_stream<'a>(
+ mut stream: ExtendedOpenAIStream<I::ResponseExtension>,
+ ) -> ExtendedPartStream<'a, I::ResponseExtension> {
+ let stream = stream!({
+ let mut tool_calls: HashMap<u32, PartialToolCall> = HashMap::new();
+ while let Some(item) = stream.next().await {
+ match item {
+ Ok(ExtendedOpenAIStreamItem::Response(part)) => {
+ if let Some(usage) = &part.usage {
+ yield Ok(PartOrExt::Part(StreamPart::Usage(usage.clone().into())))
+ }
+ let first = part.choices.first();
+ if first.is_none() {
+ continue;
+ }
+ let first = first.unwrap();
+ if let Some(content) = &first.delta.content {
+ yield Ok(PartOrExt::Part(StreamPart::Content(content.clone())));
+ }
+
+ if let Some(calls) = &first.delta.tool_calls {
+ for call in calls {
+ if let Some(function) = &call.function {
+ tool_calls
+ .entry(call.index)
+ .and_modify(|partial| {
+ if let Some(n) = &function.name {
+ partial.name = n.to_owned();
+ }
+ if let Some(a) = &function.arguments.clone() {
+ partial.json = format!("{}{}", partial.json, a);
+ }
+ if let Some(id) = &call.id {
+ partial.id = id.clone();
+ }
+ })
+ .or_insert_with(|| {
+ let mut partial = PartialToolCall::default();
+ if let Some(n) = function.name.clone() {
+ partial.name = n;
+ }
+ if let Some(a) = function.arguments.clone() {
+ partial.json = a;
+ }
+ if let Some(id) = &call.id {
+ partial.id = id.clone();
+ }
+ partial
+ });
+ }
+ }
+ }
+ if let Some(FinishReason::ToolCalls) = first.finish_reason {
+ for call in tool_calls.into_values() {
+ match ToolCall::try_from(call.clone()) {
+ Ok(call) => {
+ yield Ok(PartOrExt::Part(StreamPart::ToolCall(call)))
+ }
+ Err(e) => {
+ tracing::error!(
+ err=?e,
+ "ToolCall::try_from failed from {:#?}",
+ call
+ );
+ }
+ }
+ }
+ tool_calls = HashMap::new();
+ }
+ }
+ Ok(ExtendedOpenAIStreamItem::Extension(ext)) => {
+ // Handle provider-specific extension items (Anthropic server tools)
+ yield Ok(PartOrExt::Ext(ext));
+ }
+ Err(error) => yield Err(error.into()),
+ }
+ }
+ });
+ Box::pin(stream)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn make_openai_chat_completion_stream(
+ &mut self,
+ ) -> Result<ExtendedOpenAIStream<I::ResponseExtension>> {
+ self.request.messages = correct_message_chain(self.messages.clone());
+ self.request.tools = Some(self.toolset.openai_chatcompletion_toolset());
+ self.request.stream = Some(true);
+ self.request.stream_options = Some(ChatCompletionStreamOptions {
+ include_usage: true,
+ });
+
+ self.client.chat_stream(self.request.clone()).await
+ }
+}
+
+// anthropic sometimes doesn't return responses for their servier tools. this causes 400's
+#[tracing::instrument(skip_all)]
+fn correct_message_chain(
+ messages: Vec<ChatCompletionRequestMessage>,
+) -> Vec<ChatCompletionRequestMessage> {
+ let mut corrected = vec![];
+ let mut pending_tool_calls: Option<Vec<ChatCompletionMessageToolCall>> = None;
+ let mut i = 0;
+
+ while i < messages.len() {
+ let msg = &messages[i];
+
+ if let Some(expected) = pending_tool_calls.take() {
+ // Consume as many matching tool responses as we can
+ let mut responded: HashSet<String> = HashSet::new();
+ while i < messages.len() {
+ if let ChatCompletionRequestMessage::Tool(tool_msg) = &messages[i] {
+ responded.insert(tool_msg.tool_call_id.clone());
+ corrected.push(messages[i].clone());
+ i += 1;
+ } else {
+ break;
+ }
+ }
+ // Backfill any missing tool responses
+ for call in &expected {
+ if !responded.contains(&call.id) {
+ tracing::warn!(call_id=?call.id, "missing tool response");
+ corrected.push(ChatCompletionRequestMessage::Tool(
+ ChatCompletionRequestToolMessage {
+ tool_call_id: call.id.clone(),
+ content:
+ async_openai::types::ChatCompletionRequestToolMessageContent::Text(
+ "No response from server".into(),
+ ),
+ },
+ ));
+ }
+ }
+ } else {
+ if let ChatCompletionRequestMessage::Assistant(assistant) = msg {
+ pending_tool_calls = assistant.tool_calls.clone();
+ }
+ corrected.push(messages[i].clone());
+ i += 1;
+ }
+ }
+
+ // Handle trailing assistant with tool_calls but no responses at end of messages
+ if let Some(expected) = pending_tool_calls {
+ for call in &expected {
+ tracing::warn!(call_id=?call.id, "missing tool response");
+ corrected.push(ChatCompletionRequestMessage::Tool(
+ ChatCompletionRequestToolMessage {
+ tool_call_id: call.id.clone(),
+ content: async_openai::types::ChatCompletionRequestToolMessageContent::Text(
+ "No response from server".into(),
+ ),
+ },
+ ));
+ }
+ }
+ corrected
+}
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat/mod.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/mod.rs
new file mode 100644
index 0000000000..71d2403275
--- /dev/null
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/mod.rs
@@ -0,0 +1,10 @@
+mod agent;
+
+#[cfg(test)]
+mod test;
+
+pub use agent::*;
+
+use crate::types::Model;
+pub const MAX_RECURSIONS: u32 = 100;
+pub const TOOL_GENERATOR: Model = Model::Gemini20Flash;
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
similarity index 99%
rename from rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
rename to rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
index e1cb12ce01..9dc3855f3a 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
@@ -1,4 +1,4 @@
-use super::constant::MAX_RECURSIONS;
+use super::MAX_RECURSIONS;
use crate::openai_toolset::OpenAIToolSetExt;
use crate::tool::types::{
AsyncToolSet, PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult,
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/constant.rs b/rust/cloud-storage/ai/src/tool/tool_loop/constant.rs
index 553a8d2a56..8b13789179 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/constant.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/constant.rs
@@ -1,4 +1 @@
-use crate::types::Model;
-pub const MAX_RECURSIONS: u32 = 20;
-pub const TOOL_GENERATOR: Model = Model::Gemini20Flash;
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs b/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs
index 7191e6d79c..164d76b21b 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs
@@ -1,5 +1,4 @@
pub mod ai_client;
-pub mod chained;
pub mod chat;
pub mod cli;
pub mod constant;