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(ai): route directly to anthropic instead of openrouter

ehayescda7bde3e20a
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 7b2dfad9de..8c5b0ec803 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -46,6 +46,7 @@ name = "ai"
version = "0.1.0"
dependencies = [
"ai_format",
+ "anthropic",
"anyhow",
"async-openai",
"async-stream",
@@ -197,6 +198,26 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "anthropic"
+version = "0.1.0"
+dependencies = [
+ "async-openai",
+ "async-stream",
+ "chrono",
+ "futures",
+ "rand 0.9.0",
+ "reqwest",
+ "reqwest-eventsource",
+ "schemars",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.17",
+ "tokio",
+ "tokio-stream",
+ "tracing",
+]
+
[[package]]
name = "anyhow"
version = "1.0.95"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index aa24ca33ab..28933e9d0c 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -108,6 +108,7 @@ members = [
"user_link_cleanup_handler",
"user_quota",
"worker_trigger",
+ "anthropic"
]
[workspace.dependencies]
@@ -171,6 +172,7 @@ strum = { version = "0.27.1", features = ["derive"] }
thiserror = "2.0.0"
time = "0.3.37"
tokio = { version = "1.43.0", features = ["macros", "rt-multi-thread"] }
+tokio-stream = { version = "0.1.17" }
tokio-util = "0.7.13"
tower = { version = "0.5.1", features = ["util"] }
tower-http = { version = "0.6.1", features = [
diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.toml
index 2fcb89a75c..78c5afcf44 100644
--- a/rust/cloud-storage/ai/Cargo.toml
+++ b/rust/cloud-storage/ai/Cargo.toml
@@ -29,3 +29,4 @@ tiktoken-rs = "0.5.9"
tokio.workspace = true
tracing = { workspace = true }
utoipa = { workspace = true }
+anthropic = { path = "../anthropic" }
diff --git a/rust/cloud-storage/ai/src/chat_completion.rs b/rust/cloud-storage/ai/src/chat_completion.rs
index 0b81fc4bc2..3b5a14a46d 100644
--- a/rust/cloud-storage/ai/src/chat_completion.rs
+++ b/rust/cloud-storage/ai/src/chat_completion.rs
@@ -51,5 +51,6 @@ pub async fn get_chat_completion_openai_request(
) -> Result<String, ChatCompletionError> {
// Streaming OpenAI models directly via OpenAI
let client = OpenRouterClient::new();
+ let request = client.preprocess_request(request);
get_openai_chat_completion(client, request).await
}
diff --git a/rust/cloud-storage/ai/src/instructions.md b/rust/cloud-storage/ai/src/instructions.md
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/rust/cloud-storage/ai/src/tool/client/ai_client.rs b/rust/cloud-storage/ai/src/tool/client/ai_client.rs
index e319f056a4..507d956ce1 100644
--- a/rust/cloud-storage/ai/src/tool/client/ai_client.rs
+++ b/rust/cloud-storage/ai/src/tool/client/ai_client.rs
@@ -1,17 +1,14 @@
use super::chained::Chained;
use super::chat::Chat;
use crate::tool::types::AsyncToolSet;
-use crate::types::{OpenRouterClient, openrouter::OpenRouterConfig};
-use async_openai::Client;
-use async_openai::config::Config;
-use std::ops::Deref;
+use crate::types::AnthropicClient;
+use crate::types::Client;
use std::sync::Arc;
-pub struct AiClient<C, T, I, R>
+pub struct AiClient<I, T, R>
where
- C: Config + Send + Sync,
+ I: Client + Clone + Send + Sync,
T: Clone + Send + Sync,
- I: Deref<Target = Client<C>> + Clone + Send + Sync,
R: Clone + Send + Sync,
{
inner: I,
@@ -19,13 +16,13 @@ where
toolset: Arc<AsyncToolSet<T, R>>,
}
-impl<T, R> AiClient<OpenRouterConfig, T, OpenRouterClient, R>
+impl<T, R> AiClient<AnthropicClient, T, R>
where
T: Clone + Send + Sync,
R: Clone + Send + Sync,
{
pub fn new(toolset: AsyncToolSet<T, R>, context: T) -> Self {
- let client = OpenRouterClient::new();
+ let client = AnthropicClient::new();
let toolset = Arc::new(toolset);
Self {
inner: client,
@@ -35,14 +32,13 @@ where
}
}
-impl<C, T, I, R> AiClient<C, T, I, R>
+impl<I, T, R> AiClient<I, T, R>
where
- C: Config + Send + Sync,
+ I: Client + Clone + Send + Sync,
T: Clone + Send + Sync,
- I: Deref<Target = Client<C>> + Clone + Send + Sync,
R: Clone + Send + Sync,
{
- pub fn chat(&self) -> Chat<C, T, I, R> {
+ pub fn chat(&self) -> Chat<I, T, R> {
Chat::new(
self.inner.clone(),
self.toolset.clone(),
@@ -50,7 +46,7 @@ where
)
}
- pub fn chained(&self) -> Chained<C, T, I, R> {
+ pub fn chained(&self) -> Chained<I, T, R> {
Chained::new(
self.inner.clone(),
self.toolset.clone(),
diff --git a/rust/cloud-storage/ai/src/tool/client/chained.rs b/rust/cloud-storage/ai/src/tool/client/chained.rs
index 7f1e6bae60..0deafb7b5e 100644
--- a/rust/cloud-storage/ai/src/tool/client/chained.rs
+++ b/rust/cloud-storage/ai/src/tool/client/chained.rs
@@ -7,7 +7,7 @@
/// (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 opaquely so the calls to the `ChainedTool` are not
+/// 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
///
@@ -17,13 +17,12 @@ use crate::tool::completion::tool_completion;
use crate::tool::types::{AsyncToolSet, PartialToolCall, StreamPart, ToolCall, ToolResult};
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,
};
use anyhow::Result;
-use async_openai::Client;
-use async_openai::config::Config;
use async_openai::types::{
ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,
ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,
@@ -36,7 +35,6 @@ use futures::stream::StreamExt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
-use std::ops::Deref;
use std::sync::Arc;
struct ProcessedStream {
@@ -89,11 +87,10 @@ description: {}
.join("\n")
}
-pub struct Chained<C, T, I, R>
+pub struct Chained<I, T, R>
where
- C: Config + Send + Sync,
+ I: Client + Send + Sync,
T: Clone + Send + Sync + 'static,
- I: Deref<Target = Client<C>> + Send + Sync,
R: Send + Sync + 'static,
{
inner: I,
@@ -106,14 +103,13 @@ where
tool_call_count: usize,
}
-impl<C, T, I, R> Chained<C, T, I, R>
+impl<I, T, R> Chained<I, T, R>
where
- C: Config + Send + Sync,
+ I: Client + Send + Sync,
T: Clone + Send + Sync,
- I: Deref<Target = Client<C>> + Send + Sync,
R: Clone + Send + Sync,
{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T, R>>, context: T) -> Chained<C, T, I, R> {
+ pub fn new(client: I, toolset: Arc<AsyncToolSet<T, R>>, context: T) -> Chained<I, T, R> {
Chained {
inner: client,
toolset,
@@ -428,10 +424,6 @@ where
tracing::trace!("{:#?}", self.request);
- self.inner
- .chat()
- .create_stream(self.request.clone())
- .await
- .map_err(anyhow::Error::from)
+ self.inner.chat_stream(self.request.clone(), None).await
}
}
diff --git a/rust/cloud-storage/ai/src/tool/client/chat.rs b/rust/cloud-storage/ai/src/tool/client/chat.rs
index 415c0ce508..a49cd132d7 100644
--- a/rust/cloud-storage/ai/src/tool/client/chat.rs
+++ b/rust/cloud-storage/ai/src/tool/client/chat.rs
@@ -4,9 +4,8 @@ use crate::tool::types::{ChatCompletionStream, ToolResponse};
use crate::types::openai::message::convert_message;
use crate::types::{ChatCompletionRequest, ChatMessage, ChatMessages};
-use anyhow::{Context, Result};
-use async_openai::Client;
-use async_openai::config::Config;
+use crate::types::{Client, RequestExtensions};
+use anyhow::Result;
use async_openai::types::{
ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,
ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,
@@ -16,7 +15,6 @@ use async_openai::types::{
use async_stream::stream;
use futures::stream::StreamExt;
use std::collections::HashMap;
-use std::ops::Deref;
use std::sync::Arc;
struct ProcessedStream {
@@ -24,11 +22,10 @@ struct ProcessedStream {
pub tool_responses: Vec<ToolResponse>,
}
-pub struct Chat<C, T, I, R>
+pub struct Chat<I, T, R>
where
- C: Config + Send + Sync,
+ I: Client + Send + Sync,
T: Clone + Send + Sync + 'static,
- I: Deref<Target = Client<C>> + Send + Sync,
R: Send + Sync + 'static,
{
inner: I,
@@ -41,14 +38,13 @@ where
user_id: String,
}
-impl<C, T, I, R> Chat<C, T, I, R>
+impl<I, T, R> Chat<I, T, R>
where
- C: Config + Send + Sync,
+ I: Client + Send + Sync,
T: Clone + Send + Sync,
- I: Deref<Target = Client<C>> + Send + Sync,
R: Clone + Send + Sync,
{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T, R>>, context: T) -> Chat<C, T, I, R> {
+ pub fn new(client: I, toolset: Arc<AsyncToolSet<T, R>>, context: T) -> Chat<I, T, R> {
Chat {
inner: client,
toolset,
@@ -294,7 +290,7 @@ where
.entry(call.index)
.and_modify(|partial| {
if let Some(n) = &function.name {
- partial.name = format!("{}{}", partial.name, n);
+ partial.name = n.to_owned();
}
if let Some(a) = &function.arguments.clone() {
partial.json = format!("{}{}", partial.json, a);
@@ -342,28 +338,24 @@ where
include_usage: true,
});
- let mut request = serde_json::to_value(&self.request).context("jsonify request")?;
-
- if let serde_json::Value::Object(ref mut r) = request {
- r.insert(
- "user".into(),
- serde_json::Value::String(self.user_id.clone()),
- );
- }
+ let extensions = RequestExtensions::new(serde_json::json!(
+ {
+ "user": self.user_id.clone()
+ }
+ ))
+ .expect("invalid request extensions");
self.inner
- .chat()
- .create_stream_byot(request)
+ .chat_stream(self.request.clone(), Some(extensions))
.await
- .map_err(anyhow::Error::from)
}
}
#[cfg(test)]
mod tests {
use super::*;
+ use crate::types::noop::NoOpClient;
use crate::types::{AssistantMessagePart, ChatMessageContent, Role};
- use async_openai::config::OpenAIConfig;
use async_openai::types::{
ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,
ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,
@@ -372,8 +364,8 @@ mod tests {
};
use serde_json::json;
- fn create_mock_chat() -> Chat<OpenAIConfig, String, Box<Client<OpenAIConfig>>, String> {
- let client = Box::new(Client::new());
+ fn create_mock_chat() -> Chat<NoOpClient, String, 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/src/types/client.rs b/rust/cloud-storage/ai/src/types/client.rs
deleted file mode 100644
index 416a3e2184..0000000000
--- a/rust/cloud-storage/ai/src/types/client.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-use crate::types::openrouter::OpenRouterConfig;
-use async_openai::Client as OpenAiClient;
-
-#[derive(Clone)]
-pub struct OpenRouterClient {
- inner: OpenAiClient<OpenRouterConfig>,
-}
-
-impl OpenRouterClient {
- pub fn new() -> Self {
- OpenRouterClient {
- inner: OpenAiClient::with_config(OpenRouterConfig::new()),
- }
- }
-}
-
-impl std::ops::Deref for OpenRouterClient {
- type Target = OpenAiClient<OpenRouterConfig>;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
-}
-
-impl Default for OpenRouterClient {
- fn default() -> Self {
- Self::new()
- }
-}
diff --git a/rust/cloud-storage/ai/src/types/client/anthropic.rs b/rust/cloud-storage/ai/src/types/client/anthropic.rs
new file mode 100644
index 0000000000..d2da979e49
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/client/anthropic.rs
@@ -0,0 +1,32 @@
+use super::Client;
+
+#[derive(Clone, Debug)]
+pub struct AnthropicClient {
+ inner: anthropic::client::Client,
+}
+
+impl AnthropicClient {
+ pub fn new() -> Self {
+ let client = anthropic::client::Client::dangerously_try_from_env();
+ Self { inner: client }
+ }
+}
+
+impl Default for AnthropicClient {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Client for AnthropicClient {
+ async fn chat_stream(
+ &self,
+ request: async_openai::types::CreateChatCompletionRequest,
+ extensions: Option<super::RequestExtensions>,
+ ) -> anyhow::Result<async_openai::types::ChatCompletionResponseStream> {
+ if extensions.is_some() {
+ tracing::warn!("extensions are not yet supported");
+ }
+ Ok(self.inner.chat().create_stream_openai(request).await)
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/client/mod.rs b/rust/cloud-storage/ai/src/types/client/mod.rs
new file mode 100644
index 0000000000..4f3c53f652
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/client/mod.rs
@@ -0,0 +1,7 @@
+pub mod anthropic;
+pub mod openrouter;
+pub mod traits;
+pub use anthropic::AnthropicClient;
+pub use openrouter::OpenRouterClient;
+pub use traits::{Client, RequestExtensions};
+pub mod noop;
diff --git a/rust/cloud-storage/ai/src/types/client/noop.rs b/rust/cloud-storage/ai/src/types/client/noop.rs
new file mode 100644
index 0000000000..5f19f2dd24
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/client/noop.rs
@@ -0,0 +1,15 @@
+use super::traits::Client;
+use anyhow::anyhow;
+
+#[derive(Debug, Clone, Default)]
+pub struct NoOpClient;
+
+impl Client for NoOpClient {
+ async fn chat_stream(
+ &self,
+ _: async_openai::types::CreateChatCompletionRequest,
+ _: Option<super::RequestExtensions>,
+ ) -> anyhow::Result<async_openai::types::ChatCompletionResponseStream> {
+ Err(anyhow!("noop"))
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/client/openrouter/client.rs b/rust/cloud-storage/ai/src/types/client/openrouter/client.rs
new file mode 100644
index 0000000000..59977bc15e
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/client/openrouter/client.rs
@@ -0,0 +1,64 @@
+use super::config::OpenRouterConfig;
+use crate::types::client::traits::{Client, RequestExtensions};
+use crate::types::{Model, ModelWithMetadataAndProvider};
+use anyhow::Context;
+use async_openai::Client as OpenAiClient;
+use async_openai::types::CreateChatCompletionRequest;
+
+#[derive(Clone)]
+pub struct OpenRouterClient {
+ inner: OpenAiClient<OpenRouterConfig>,
+}
+
+impl OpenRouterClient {
+ pub fn new() -> Self {
+ OpenRouterClient {
+ inner: OpenAiClient::with_config(OpenRouterConfig::new()),
+ }
+ }
+}
+
+impl std::ops::Deref for OpenRouterClient {
+ type Target = OpenAiClient<OpenRouterConfig>;
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+
+impl Default for OpenRouterClient {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl OpenRouterClient {
+ pub fn preprocess_request(
+ &self,
+ mut request: CreateChatCompletionRequest,
+ ) -> CreateChatCompletionRequest {
+ let model = serde_json::from_str::<Model>(&request.model).unwrap_or(Model::Gemini20Flash);
+ let model_str = format!("{}/{}", model.provider(), model);
+ request.model = model_str;
+ request
+ }
+}
+
+impl Client for OpenRouterClient {
+ async fn chat_stream(
+ &self,
+ request: async_openai::types::CreateChatCompletionRequest,
+ extensions: Option<RequestExtensions>,
+ ) -> anyhow::Result<async_openai::types::ChatCompletionResponseStream> {
+ let request = self.preprocess_request(request);
+ let request = if let Some(ext) = extensions {
+ self.extend_request(request, ext)
+ } else {
+ serde_json::to_value(request).context("failed to jsonfiy request")
+ }?;
+ self.inner
+ .chat()
+ .create_stream_byot(request)
+ .await
+ .map_err(anyhow::Error::from)
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/providers/openrouter.rs b/rust/cloud-storage/ai/src/types/client/openrouter/config.rs
similarity index 91%
rename from rust/cloud-storage/ai/src/types/providers/openrouter.rs
rename to rust/cloud-storage/ai/src/types/client/openrouter/config.rs
index c93bb32e44..afb9a38adb 100644
--- a/rust/cloud-storage/ai/src/types/providers/openrouter.rs
+++ b/rust/cloud-storage/ai/src/types/client/openrouter/config.rs
@@ -5,9 +5,8 @@ use reqwest::header::{AUTHORIZATION, HeaderMap};
use secrecy::{ExposeSecret, SecretBox, SecretString};
lazy_static! {
- static ref OPEN_ROUTER_CONFIG: OpenRouterConfig = try_from_env()
- .context("Failed to load OpenRouter Config")
- .unwrap();
+ static ref OPEN_ROUTER_CONFIG: OpenRouterConfig =
+ try_from_env().expect("Failed to load OpenRouter Config");
}
const OPEN_ROUTER_BASE_URL: &str = "https://openrouter.ai/api/v1";
diff --git a/rust/cloud-storage/ai/src/types/client/openrouter/mod.rs b/rust/cloud-storage/ai/src/types/client/openrouter/mod.rs
new file mode 100644
index 0000000000..38ac6f60e0
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/client/openrouter/mod.rs
@@ -0,0 +1,5 @@
+mod client;
+mod config;
+
+pub use client::OpenRouterClient;
+pub use config::OpenRouterConfig;
diff --git a/rust/cloud-storage/ai/src/types/client/traits.rs b/rust/cloud-storage/ai/src/types/client/traits.rs
new file mode 100644
index 0000000000..53888f95b4
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/client/traits.rs
@@ -0,0 +1,50 @@
+use anyhow::{Context, Result};
+use async_openai::types::{ChatCompletionResponseStream, CreateChatCompletionRequest};
+use serde::Serialize;
+
+#[derive(Clone, Debug)]
+pub struct RequestExtensions(serde_json::Value);
+
+impl RequestExtensions {
+ pub fn new(extensions: impl Serialize) -> Result<Self> {
+ let extensions = serde_json::to_value(extensions).context("serialization")?;
+ match extensions {
+ obj @ serde_json::Value::Object(_) => Ok(Self(obj)),
+ _ => Err(anyhow::anyhow!("extensions must be an object")),
+ }
+ }
+
+ pub fn into_inner(self) -> serde_json::Value {
+ self.0
+ }
+}
+
+pub trait Client {
+ fn chat_stream(
+ &self,
+ request: CreateChatCompletionRequest,
+ extensions: Option<RequestExtensions>,
+ ) -> impl Future<Output = Result<ChatCompletionResponseStream>> + Send;
+
+ fn extend_request(
+ &self,
+ request: CreateChatCompletionRequest,
+ extensions: RequestExtensions,
+ ) -> Result<serde_json::Value> {
+ fn dumb_merge(a: serde_json::Value, b: serde_json::Value) -> serde_json::Value {
+ match (a, b) {
+ (serde_json::Value::Object(mut oa), serde_json::Value::Object(ob)) => {
+ for (k, v) in ob.into_iter() {
+ oa.insert(k, v);
+ }
+ serde_json::Value::Object(oa)
+ }
+ (a, _) => a,
+ }
+ }
+
+ let request = serde_json::to_value(request).context("jsonify request")?;
+
+ Ok(dumb_merge(request, extensions.into_inner()))
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/model/metadata.rs b/rust/cloud-storage/ai/src/types/model/metadata.rs
index e2f06b4552..a0ce75c873 100644
--- a/rust/cloud-storage/ai/src/types/model/metadata.rs
+++ b/rust/cloud-storage/ai/src/types/model/metadata.rs
@@ -6,18 +6,7 @@ use utoipa::ToSchema;
#[derive(Serialize, Deserialize, Debug, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ModelMetadata {
- /// A description of the model
- pub description: String,
- /// The token size of the context window
pub context_window: i32,
- /// Scale of speed from 0 to 5
- pub speed: i32,
- /// Scale of quality from 0 to 5
- pub quality: i32,
- // Whether the model is premium or not (free or paid)
- pub premium: bool,
- /// The display name of the model
- pub display_name: String,
}
#[derive(Display, Debug, Serialize, Deserialize, ToSchema, PartialEq, PartialOrd, Clone)]
@@ -45,130 +34,57 @@ impl ModelWithMetadataAndProvider for Model {
fn metadata(&self) -> ModelMetadata {
match self {
Model::Gemini25Pro => ModelMetadata {
- description: "Google Gemini 2.5 Pro is the latest and most intelligent model for complex tasks".to_string(),
context_window: 1_000_000,
- speed: 4,
- quality: 5,
- premium: true,
- display_name: "Gemini 2.5 Pro".to_string()
},
Model::OpenAiGpt5 => ModelMetadata {
- description: "OpenAI GPT-41 is the latest high intelligence model for complex, multi-step tasks".to_string(),
context_window: 400_000,
- speed: 5,
- quality: 5,
- premium: false,
- display_name: "GPT-5".to_string()
},
Model::OpenAiGpt41 => ModelMetadata {
- description: "OpenAI GPT-41 is the latest high intelligence model for complex, multi-step tasks".to_string(),
context_window: 1_047_576,
- speed: 4,
- quality: 5,
- premium: true,
- display_name: "GPT-4.1".to_string()
},
Model::OpenAIGPT4o => ModelMetadata {
- description: "OpenAI GPT-4o is a high-intelligence flagship model for complex, multi-step tasks".to_string(),
context_window: 128000,
- speed: 4,
- quality: 5,
- premium: true,
- display_name: "GPT-4o".to_string(),
},
Model::OpenAIo1 => ModelMetadata {
- description: "OpenAI o1 is an advanced reasoning model optimized for complex problem-solving through deep, multi-step analysis".to_string(),
context_window: 128000,
- speed: 0,
- quality: 5,
- premium: true,
- display_name: "o1".to_string(),
-
},
Model::OpenAIo3 => ModelMetadata {
- description: "OpenAI o3 is an advanced reasoning model optimized for complex problem-solving through deep, multi-step analysis".to_string(),
context_window: 200_000,
- speed: 0,
- quality: 5,
- premium: true,
- display_name: "o3".to_string(),
-
},
Model::Gemini20Flash => ModelMetadata {
- description: "Gemini 2.0 Flash is a fast and powerful model for complex reasoning tasks".to_string(),
context_window: 1_048_576,
- speed: 5,
- quality: 4,
- premium: false,
- display_name: "Gemini 2.0 Flash".to_string(),
},
Model::Gemini20FlashLite => ModelMetadata {
- description: "I am speed".to_string(),
context_window: 1_048_576,
- speed: 5,
- quality: 3,
- premium: false,
- display_name: "Gemini 2.0 Flash Lite".to_string()
},
Model::Gemini15Pro => ModelMetadata {
- description: "Gemini 1.5 Pro is a large model for complex reasoning with large documents".to_string(),
context_window: 2_097_152,
- speed: 2,
- quality: 4,
- premium: true,
- display_name: "Gemini 1.5 Pro".to_string(),
},
Model::Claude35Sonnet => ModelMetadata {
- description: "Claude 3.5 Sonnet is a strong workhorse model trained by Anthropic".to_string(),
context_window: 200_000,
- speed: 4,
- quality: 4,
- premium: true,
- display_name: "Claude 3.5 Sonnet".to_string(),
},
Model::Claude37Sonnet => ModelMetadata {
- description: "Claude 3.7 Sonnet is the flagship large language model trained by Anthropic".to_string(),
context_window: 200_000,
- speed: 4,
- quality: 5,
- premium: true,
- display_name: "Claude 3.7 Sonnet".to_string(),
},
-
+ Model::Claude45Sonnet => ModelMetadata {
+ context_window: 200_000,
+ },
+ Model::Claude45Haiku => ModelMetadata {
+ context_window: 200_000,
+ },
Model::Claude4Sonnet => ModelMetadata {
- description: "Claude 4.0 Sonnet is the flagship large language model trained by Anthropic".to_string(),
context_window: 200_000,
- speed: 4,
- quality: 5,
- premium: true,
- display_name: "Claude 4.0 Sonnet".to_string(),
},
-
Model::OpenAIGPT4oMini => ModelMetadata {
- description: "OpenAI GPT-4o Mini is a small model for complex reasoning tasks".to_string(),
context_window: 128_000,
- speed: 4,
- quality: 2,
- premium: false,
- display_name: "GPT-4o Mini".to_string(),
},
Model::OpenAIGPT4oSearchPreview => ModelMetadata {
- description: "OpenAI GPT-4o-Search-Preview is a strong model for internet search".to_string(),
context_window: 128_000,
- speed: 4,
- quality: 4,
- premium: false,
- display_name: "GPT-4o Search Preview".to_string(),
},
Model::OpenAIGgpt4oMiniSearchPreview => ModelMetadata {
- description: "OpenAI GPT-4o-Mini-Search-Preview is a lightweight model for internet search".to_string(),
context_window: 128_000,
- speed: 4,
- quality: 2,
- premium: false,
- display_name: "GPT-4o Search Preview".to_string(),
- }
+ },
}
}
@@ -192,6 +108,8 @@ impl ModelWithMetadataAndProvider for Model {
Model::Claude4Sonnet => Provider::Anthropic,
Model::Claude37Sonnet => Provider::Anthropic,
Model::Claude35Sonnet => Provider::Anthropic,
+ Model::Claude45Sonnet => Provider::Anthropic,
+ Model::Claude45Haiku => Provider::Anthropic,
// XAI models //
}
}
diff --git a/rust/cloud-storage/ai/src/types/model/mod.rs b/rust/cloud-storage/ai/src/types/model/mod.rs
index e11529b7ac..8724f58f22 100644
--- a/rust/cloud-storage/ai/src/types/model/mod.rs
+++ b/rust/cloud-storage/ai/src/types/model/mod.rs
@@ -21,68 +21,76 @@ pub use metadata::*;
)]
pub enum Model {
// Google models ------------------------------------------------------------ //
- #[strum(serialize = "google/gemini-2.5-pro")]
- #[serde(rename = "google/gemini-2.5-pro")]
+ #[strum(serialize = "gemini-2.5-pro")]
+ #[serde(rename = "gemini-2.5-pro")]
Gemini25Pro,
- #[strum(serialize = "google/gemini-2.0-flash-001")]
- #[serde(rename = "google/gemini-2.0-flash-001")]
+ #[strum(serialize = "gemini-2.0-flash-001")]
+ #[serde(rename = "gemini-2.0-flash-001")]
Gemini20Flash,
- #[strum(serialize = "google/gemini-2.0-flash-lite-001")]
- #[serde(rename = "google/gemini-2.0-flash-lite-001")]
+ #[strum(serialize = "gemini-2.0-flash-lite-001")]
+ #[serde(rename = "gemini-2.0-flash-lite-001")]
Gemini20FlashLite,
- #[serde(rename = "google/gemini-pro-1.5")]
- #[strum(serialize = "google/gemini-pro-1.5")]
+ #[serde(rename = "gemini-pro-1.5")]
+ #[strum(serialize = "gemini-pro-1.5")]
Gemini15Pro,
// OpenAI models ------------------------------------------------------------ //
- #[serde(rename = "openai/gpt-5")]
- #[strum(serialize = "openai/gpt-5")]
+ #[serde(rename = "gpt-5")]
+ #[strum(serialize = "gpt-5")]
OpenAiGpt5,
- #[serde(rename = "openai/gpt-4.1")]
- #[strum(serialize = "openai/gpt-4.1")]
+ #[serde(rename = "gpt-4.1")]
+ #[strum(serialize = "gpt-4.1")]
OpenAiGpt41,
- #[strum(serialize = "openai/gpt-4o")]
- #[serde(rename = "openai/gpt-4o")]
+ #[strum(serialize = "gpt-4o")]
+ #[serde(rename = "gpt-4o")]
OpenAIGPT4o,
- #[strum(serialize = "openai/gpt-4o-mini")]
- #[serde(rename = "openai/gpt-4o-mini")]
+ #[strum(serialize = "gpt-4o-mini")]
+ #[serde(rename = "gpt-4o-mini")]
OpenAIGPT4oMini,
- #[strum(serialize = "openai/o1")]
- #[serde(rename = "openai/o1")]
+ #[strum(serialize = "o1")]
+ #[serde(rename = "o1")]
OpenAIo1,
- #[strum(serialize = "openai/gpt-4o-search-preview")]
- #[serde(rename = "openai/gpt-4o-search-preview")]
+ #[strum(serialize = "gpt-4o-search-preview")]
+ #[serde(rename = "gpt-4o-search-preview")]
OpenAIGPT4oSearchPreview,
- #[strum(serialize = "openai/gpt-4o-mini-search-preview")]
- #[serde(rename = "openai/gpt-4o-mini-search-preview")]
+ #[strum(serialize = "gpt-4o-mini-search-preview")]
+ #[serde(rename = "gpt-4o-mini-search-preview")]
// NB typo OpenAI**G**gpt
OpenAIGgpt4oMiniSearchPreview,
- #[strum(serialize = "openai/o3")]
- #[serde(rename = "openai/o3")]
+ #[strum(serialize = "o3")]
+ #[serde(rename = "o3")]
OpenAIo3,
- #[serde(rename = "anthropic/claude-3.5-sonnet")]
- #[strum(serialize = "anthropic/claude-3.5-sonnet")]
+ #[serde(rename = "claude-3-5-sonnet")]
+ #[strum(serialize = "claude-3-5-sonnet")]
Claude35Sonnet,
- #[serde(rename = "anthropic/claude-3.7-sonnet")]
- #[strum(serialize = "anthropic/claude-3.7-sonnet")]
+ #[serde(rename = "claude-3-7-sonnet")]
+ #[strum(serialize = "claude-3-7-sonnet")]
Claude37Sonnet,
- #[serde(rename = "anthropic/claude-sonnet-4")]
- #[strum(serialize = "anthropic/claude-sonnet-4")]
- #[default]
+ #[serde(rename = "claude-sonnet-4")]
+ #[strum(serialize = "claude-sonnet-4")]
Claude4Sonnet,
+
+ #[serde(rename = "claude-sonnet-4-5")]
+ #[strum(serialize = "claude-sonnet-4-5")]
+ Claude45Sonnet,
+
+ #[serde(rename = "claude-haiku-4-5")]
+ #[strum(serialize = "claude-haiku-4-5")]
+ #[default]
+ Claude45Haiku,
}
pub mod constants {
@@ -104,6 +112,8 @@ pub mod constants {
pub const CLAUDE_35_SONNET: &str = "claude-3.5-sonnet";
pub const CLAUDE_37_SONNET: &str = "claude-3.7-sonnet";
pub const CLAUDE_4_SONNET: &str = "claude-sonnet-4";
+ pub const CLAUDE_45_SONNET: &str = "claude-4.5-sonnet";
+ pub const CLAUDE_45_HAIKU: &str = "claude-4.5-haiku";
}
/// String versions of providers
@@ -134,6 +144,8 @@ impl Model {
Model::Claude35Sonnet => (ANTHROPIC, CLAUDE_35_SONNET),
Model::Claude37Sonnet => (ANTHROPIC, CLAUDE_37_SONNET),
Model::Claude4Sonnet => (ANTHROPIC, CLAUDE_4_SONNET),
+ Model::Claude45Sonnet => (ANTHROPIC, CLAUDE_45_SONNET),
+ Model::Claude45Haiku => (ANTHROPIC, CLAUDE_45_HAIKU),
}
}
pub fn from_model_str(model: &str) -> Option<Self> {
@@ -152,7 +164,8 @@ impl Model {
OPEN_AI_O3 => Model::OpenAIo3,
CLAUDE_35_SONNET => Model::Claude35Sonnet,
CLAUDE_37_SONNET => Model::Claude37Sonnet,
- CLAUDE_4_SONNET => Model::Claude4Sonnet,
+ CLAUDE_45_SONNET => Model::Claude45Sonnet,
+ CLAUDE_45_HAIKU => Model::Claude45Haiku,
_unknown => return None,
})
}
diff --git a/rust/cloud-storage/ai/src/types/providers/mod.rs b/rust/cloud-storage/ai/src/types/providers/mod.rs
index d2e5165e48..d8c308735b 100644
--- a/rust/cloud-storage/ai/src/types/providers/mod.rs
+++ b/rust/cloud-storage/ai/src/types/providers/mod.rs
@@ -1,2 +1 @@
pub mod openai;
-pub mod openrouter;
diff --git a/rust/cloud-storage/anthropic/Cargo.toml b/rust/cloud-storage/anthropic/Cargo.toml
new file mode 100644
index 0000000000..af2f97c67f
--- /dev/null
+++ b/rust/cloud-storage/anthropic/Cargo.toml
@@ -0,0 +1,28 @@
+[package]
+edition = "2024"
+name = "anthropic"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["openai"]
+openai = ["dep:async-openai"]
+
+[dev-dependencies]
+rand = { workspace = true }
+
+
+[dependencies]
+tokio = { workspace = true, features = ["sync"]}
+async-stream = { workspace = true }
+futures = { workspace = true }
+reqwest = { workspace = true }
+reqwest-eventsource = "0.6.0"
+schemars = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+tokio-stream = { workspace = true }
+async-openai = { workspace = true, optional = true}
+chrono.workspace = true
diff --git a/rust/cloud-storage/anthropic/README.md b/rust/cloud-storage/anthropic/README.md
new file mode 100644
index 0000000000..29a305f7fa
--- /dev/null
+++ b/rust/cloud-storage/anthropic/README.md
@@ -0,0 +1,10 @@
+An SDK for the anthropic api
+
+This mostly follows the patterns established by https://github.com/64bit/async-openai.
+
+This implementation is incomplete and only implements the functionality that is already used
+_for chat_ in the ai crate.
+
+The `openai` feature adds a dependency on the `async-openai` crate and defines mappings
+from and to openai request and response types respectively. The idea is to use the `v1/chat/completions` api
+as the standard. Most open source models adhere to this standard and this is the api used by openrouter.
diff --git a/rust/cloud-storage/anthropic/examples/chat.rs b/rust/cloud-storage/anthropic/examples/chat.rs
new file mode 100644
index 0000000000..616a1eb3c5
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/chat.rs
@@ -0,0 +1,80 @@
+use std::io::Write;
+use std::process::exit;
+
+use anthropic::client::Client;
+use anthropic::types::request::{
+ CreateMessageRequestBody, RequestContent, RequestMessage, Role, SystemPrompt,
+};
+use anthropic::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use futures::StreamExt;
+
+#[tokio::main]
+async fn main() {
+ let client = Client::dangerously_try_from_env();
+ let mut request = CreateMessageRequestBody::default();
+ request.max_tokens = 1000;
+ request.system = Some(SystemPrompt::Text(
+ "You are donkey boy. You are to refer to yourself only as donkey boy".into(),
+ ));
+ request.model = "claude-haiku-4-5".into();
+ let mut out = std::io::stdout();
+
+ loop {
+ write!(out, ">>> ").expect("io");
+ out.flush().expect("io");
+
+ let mut user_input = String::new();
+ std::io::stdin().read_line(&mut user_input).expect("io");
+ let message = RequestMessage {
+ role: Role::User,
+ content: RequestContent::Text(user_input),
+ };
+ request.messages.push(message);
+ let chat = client.chat();
+ let mut stream = chat.create_stream(request.clone()).await;
+ let mut assistant_message = String::new();
+
+ while let Some(event) = stream.next().await {
+ if let Err(error) = event {
+ match error {
+ other => {
+ writeln!(out, "\nerror: {:#?}", other).expect("io");
+ exit(1);
+ }
+ }
+ } else {
+ let event = event.unwrap();
+ let response_text = match event {
+ StreamEvent::MessageDelta { delta, .. } => match delta.content {
+ Some(anthropic::types::response::Content::Text(txt)) => txt,
+ Some(anthropic::types::response::Content::Array(arr)) => {
+ format!("{:?}", arr)
+ }
+ _ => "".into(),
+ },
+ StreamEvent::ContentBlockDelta { delta, .. } => match delta {
+ ContentDeltaEvent::StartTextDelta { text } => text,
+ ContentDeltaEvent::TextDelta { text } => text,
+ ContentDeltaEvent::ThinkingDelta { thinking } => thinking,
+ _ => "other-block-delta\n".into(),
+ },
+ StreamEvent::ContentBlockStart { .. } => "content-block-start\n".into(),
+ StreamEvent::ContentBlockStop { .. } => "\ncontent-block-stop\n".into(),
+ StreamEvent::Ping => "".into(),
+ StreamEvent::MessageStart { .. } => "message-start\n".into(),
+ StreamEvent::MessageStop { .. } => "message-stop\n".into(),
+ StreamEvent::Error { error } => format!("error: {:?}", error),
+ };
+ write!(out, "{}", response_text).expect("io");
+ assistant_message.push_str(&response_text);
+ out.flush().expect("io");
+ }
+ }
+ let response = RequestMessage {
+ role: Role::Assistant,
+ content: RequestContent::Text(assistant_message),
+ };
+ request.messages.push(response);
+ writeln!(out).expect("io");
+ }
+}
diff --git a/rust/cloud-storage/anthropic/examples/chat_openai.rs b/rust/cloud-storage/anthropic/examples/chat_openai.rs
new file mode 100644
index 0000000000..d74218aa0a
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/chat_openai.rs
@@ -0,0 +1,89 @@
+use std::io::Write;
+use std::process::exit;
+
+use anthropic::client::Client;
+use anthropic::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use async_openai::types::{
+ ChatCompletionRequestAssistantMessage, ChatCompletionRequestAssistantMessageContent,
+ ChatCompletionRequestMessage, ChatCompletionRequestSystemMessageArgs,
+ ChatCompletionRequestUserMessage, ChatCompletionRequestUserMessageContent,
+ CreateChatCompletionRequestArgs,
+};
+use futures::StreamExt;
+
+#[tokio::main]
+async fn main() {
+ let client = Client::dangerously_try_from_env();
+
+ let mut request = CreateChatCompletionRequestArgs::default()
+ .model("claude-haiku-4-5")
+ .max_completion_tokens(1000_u32)
+ .messages([ChatCompletionRequestSystemMessageArgs::default()
+ .content("you are donkey boy. refer to yourself only as donkey boy")
+ .build()
+ .expect("system message")
+ .into()])
+ .build()
+ .expect("request");
+
+ let mut out = std::io::stdout();
+
+ loop {
+ write!(out, ">>> ").expect("io");
+ out.flush().expect("io");
+
+ let mut user_input = String::new();
+ std::io::stdin().read_line(&mut user_input).expect("io");
+ let message = ChatCompletionRequestMessage::User(ChatCompletionRequestUserMessage {
+ content: ChatCompletionRequestUserMessageContent::Text(user_input),
+ name: None,
+ });
+ request.messages.push(message);
+ let chat = client.chat();
+ let mut stream = chat.create_stream(request.clone()).await;
+ let mut assistant_response = String::new();
+
+ while let Some(event) = stream.next().await {
+ if let Err(error) = event {
+ match error {
+ other => {
+ writeln!(out, "\nerror: {:#?}", other).expect("io");
+ exit(1);
+ }
+ }
+ } else {
+ let event = event.unwrap();
+ let response_text = match event {
+ StreamEvent::MessageDelta { delta, .. } => match delta.content {
+ Some(anthropic::types::response::Content::Text(txt)) => txt,
+ Some(anthropic::types::response::Content::Array(arr)) => {
+ format!("{:?}", arr)
+ }
+ _ => "".into(),
+ },
+ StreamEvent::ContentBlockDelta { delta, .. } => match delta {
+ ContentDeltaEvent::StartTextDelta { text } => text,
+ ContentDeltaEvent::TextDelta { text } => text,
+ ContentDeltaEvent::ThinkingDelta { thinking } => thinking,
+ _ => "other-block-delta\n".into(),
+ },
+ StreamEvent::ContentBlockStart { .. } => "content-block-start\n".into(),
+ StreamEvent::ContentBlockStop { .. } => "\ncontent-block-stop\n".into(),
+ StreamEvent::Ping => "".into(),
+ StreamEvent::MessageStart { .. } => "message-start\n".into(),
+ StreamEvent::MessageStop { .. } => "message-stop\n".into(),
+ StreamEvent::Error { error } => format!("error: {:?}", error),
+ };
+ write!(out, "{}", response_text).expect("io");
+ assistant_response.push_str(&response_text);
+ out.flush().expect("io");
+ }
+ }
+ let mut response = ChatCompletionRequestAssistantMessage::default();
+ response.content = Some(ChatCompletionRequestAssistantMessageContent::Text(
+ assistant_response,
+ ));
+ request.messages.push(response.into());
+ writeln!(out).expect("io");
+ }
+}
diff --git a/rust/cloud-storage/anthropic/examples/only_openai_chat.rs b/rust/cloud-storage/anthropic/examples/only_openai_chat.rs
new file mode 100644
index 0000000000..09976ecd97
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/only_openai_chat.rs
@@ -0,0 +1,42 @@
+// copied from https://github.com/64bit/async-openai/blob/main/examples/chat-stream/src/main.rs
+use std::error::Error;
+use std::io::{Write, stdout};
+
+use async_openai::types::ChatCompletionRequestUserMessageArgs;
+use async_openai::types::CreateChatCompletionRequestArgs;
+use futures::StreamExt;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+ let request = CreateChatCompletionRequestArgs::default()
+ .model("claude-haiku-4-5")
+ .max_tokens(512u32)
+ .messages([ChatCompletionRequestUserMessageArgs::default()
+ .content("Write a marketing blog praising and introducing Rust library async-openai")
+ .build()?
+ .into()])
+ .build()?;
+ println!("{:#?}", request);
+
+ let client = anthropic::client::Client::dangerously_try_from_env();
+ let mut stream = client.chat().create_stream_openai(request).await;
+
+ let mut lock = stdout().lock();
+ while let Some(result) = stream.next().await {
+ match result {
+ Ok(response) => {
+ response.choices.iter().for_each(|chat_choice| {
+ if let Some(ref content) = chat_choice.delta.content {
+ write!(lock, "{}", content).unwrap();
+ }
+ });
+ }
+ Err(err) => {
+ writeln!(lock, "error: {err:?}").unwrap();
+ }
+ }
+ stdout().flush()?;
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/anthropic/examples/only_openai_tools.rs b/rust/cloud-storage/anthropic/examples/only_openai_tools.rs
new file mode 100644
index 0000000000..9085da3cfa
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/only_openai_tools.rs
@@ -0,0 +1,259 @@
+// copied from https://github.com/64bit/async-openai/blob/main/examples/tool-call-stream/src/main.rs
+use std::collections::HashMap;
+use std::error::Error;
+use std::io::{Write, stdout};
+use std::sync::Arc;
+
+use async_openai::types::CreateChatCompletionRequestArgs;
+use async_openai::types::{
+ ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessageArgs,
+ ChatCompletionRequestMessage, ChatCompletionRequestToolMessageArgs,
+ ChatCompletionRequestUserMessageArgs, ChatCompletionToolArgs, ChatCompletionToolType,
+ FinishReason, FunctionCall, FunctionObjectArgs,
+};
+use futures::StreamExt;
+use rand::prelude::*;
+use serde_json::{Value, json};
+use tokio::sync::Mutex;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let user_prompt = "What's the weather like in Boston and Atlanta?";
+ let tools = vec![
+ ChatCompletionToolArgs::default()
+ .r#type(ChatCompletionToolType::Function)
+ .function(
+ FunctionObjectArgs::default()
+ .name("get_current_weather")
+ .description("Get the current weather in a given location")
+ .parameters(json!({
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "The city and state, e.g. San Francisco, CA",
+ },
+ "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] },
+ },
+ "required": ["location"],
+ }))
+ .build()?,
+ )
+ .build()?,
+ ];
+ let request = CreateChatCompletionRequestArgs::default()
+ .max_tokens(6000_u32)
+ .model("claude-haiku-4-5")
+ .messages([ChatCompletionRequestUserMessageArgs::default()
+ .content(user_prompt)
+ .build()?
+ .into()])
+ .tools(tools.clone())
+ .build()?;
+
+ let client = anthropic::client::Client::dangerously_try_from_env();
+ let mut stream = client.chat().create_stream_openai(request).await;
+
+ let tool_call_states: Arc<Mutex<HashMap<(u32, u32), ChatCompletionMessageToolCall>>> =
+ Arc::new(Mutex::new(HashMap::new()));
+
+ while let Some(result) = stream.next().await {
+ match result {
+ Ok(response) => {
+ for chat_choice in response.choices {
+ let function_responses: Arc<
+ Mutex<Vec<(ChatCompletionMessageToolCall, Value)>>,
+ > = Arc::new(Mutex::new(Vec::new()));
+ if let Some(tool_calls) = chat_choice.delta.tool_calls {
+ for tool_call_chunk in tool_calls.into_iter() {
+ let key = (chat_choice.index, tool_call_chunk.index);
+ let states = tool_call_states.clone();
+ let tool_call_data = tool_call_chunk.clone();
+
+ let mut states_lock = states.lock().await;
+ let state = states_lock.entry(key).or_insert_with(|| {
+ ChatCompletionMessageToolCall {
+ id: tool_call_data.id.clone().unwrap_or_default(),
+ r#type: ChatCompletionToolType::Function,
+ function: FunctionCall {
+ name: tool_call_data
+ .function
+ .as_ref()
+ .and_then(|f| f.name.clone())
+ .unwrap_or_default(),
+ arguments: tool_call_data
+ .function
+ .as_ref()
+ .and_then(|f| f.arguments.clone())
+ .unwrap_or_default(),
+ },
+ }
+ });
+ if let Some(arguments) = tool_call_chunk
+ .function
+ .as_ref()
+ .and_then(|f| f.arguments.as_ref())
+ {
+ state.function.arguments.push_str(arguments);
+ }
+ }
+ }
+ if let Some(finish_reason) = &chat_choice.finish_reason {
+ if matches!(finish_reason, FinishReason::ToolCalls) {
+ let tool_call_states_clone = tool_call_states.clone();
+
+ let tool_calls_to_process = {
+ let states_lock = tool_call_states_clone.lock().await;
+ states_lock
+ .iter()
+ .map(|(_key, tool_call)| {
+ let name = tool_call.function.name.clone();
+ let args = tool_call.function.arguments.clone();
+ let tool_call_clone = tool_call.clone();
+ (name, args, tool_call_clone)
+ })
+ .collect::<Vec<_>>()
+ };
+
+ let mut handles = Vec::new();
+ for (name, args, tool_call_clone) in tool_calls_to_process {
+ let response_content_clone = function_responses.clone();
+ let handle = tokio::spawn(async move {
+ let response_content = call_fn(&name, &args).await.unwrap();
+
+ let mut function_responses_lock =
+ response_content_clone.lock().await;
+ function_responses_lock
+ .push((tool_call_clone, response_content));
+ });
+ handles.push(handle);
+ }
+
+ for handle in handles {
+ handle.await.unwrap();
+ }
+
+ let function_responses_clone = function_responses.clone();
+ let function_responses_lock = function_responses_clone.lock().await;
+ let mut messages: Vec<ChatCompletionRequestMessage> = vec![
+ ChatCompletionRequestUserMessageArgs::default()
+ .content(user_prompt)
+ .build()?
+ .into(),
+ ];
+
+ let tool_calls: Vec<ChatCompletionMessageToolCall> =
+ function_responses_lock
+ .iter()
+ .map(|tc| tc.0.clone())
+ .collect();
+
+ let assistant_messages: ChatCompletionRequestMessage =
+ ChatCompletionRequestAssistantMessageArgs::default()
+ .tool_calls(tool_calls)
+ .build()
+ .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
+ .unwrap()
+ .into();
+
+ let tool_messages: Vec<ChatCompletionRequestMessage> =
+ function_responses_lock
+ .iter()
+ .map(|tc| {
+ ChatCompletionRequestToolMessageArgs::default()
+ .content(tc.1.to_string())
+ .tool_call_id(tc.0.id.clone())
+ .build()
+ .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
+ .unwrap()
+ .into()
+ })
+ .collect();
+
+ messages.push(assistant_messages);
+ messages.extend(tool_messages);
+
+ let request = CreateChatCompletionRequestArgs::default()
+ .max_tokens(6000_u32)
+ .model("claude-haiku-4-5")
+ .messages(messages)
+ .tools(tools.clone())
+ .build()
+ .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
+
+ let mut stream = client.chat().create_stream_openai(request).await;
+
+ let mut response_content = String::new();
+ let mut lock = stdout().lock();
+ while let Some(result) = stream.next().await {
+ match result {
+ Ok(response) => {
+ for chat_choice in response.choices.iter() {
+ if let Some(ref content) = chat_choice.delta.content {
+ write!(lock, "{}", content).unwrap();
+ response_content.push_str(content);
+ }
+ }
+ }
+ Err(err) => {
+ return Err(Box::new(err) as Box<dyn std::error::Error>);
+ }
+ }
+ }
+ }
+ }
+
+ if let Some(content) = &chat_choice.delta.content {
+ let mut lock = stdout().lock();
+ write!(lock, "{}", content).unwrap();
+ }
+ }
+ }
+ Err(err) => {
+ let mut lock = stdout().lock();
+ writeln!(lock, "error: {err:?}").unwrap();
+ }
+ }
+ stdout()
+ .flush()
+ .map_err(|e| Box::new(e) as Box<dyn Error>)?;
+ }
+
+ Ok(())
+}
+
+async fn call_fn(name: &str, args: &str) -> Result<Value, Box<dyn std::error::Error>> {
+ println!("call function! {}({})", name, args);
+ let mut available_functions: HashMap<&str, fn(&str, &str) -> serde_json::Value> =
+ HashMap::new();
+ available_functions.insert("get_current_weather", get_current_weather);
+
+ let function_args: serde_json::Value = args.parse().unwrap();
+
+ let location = function_args["location"].as_str().unwrap();
+ let unit = function_args["unit"].as_str().unwrap_or("fahrenheit");
+ let function = available_functions.get(name).unwrap();
+ let function_response = function(location, unit);
+ Ok(function_response)
+}
+
+fn get_current_weather(location: &str, unit: &str) -> serde_json::Value {
+ let mut rng = rand::thread_rng();
+
+ let temperature: i32 = rng.gen_range(20..=55);
+
+ let forecasts = [
+ "sunny", "cloudy", "overcast", "rainy", "windy", "foggy", "snowy",
+ ];
+
+ let forecast = forecasts.choose(&mut rng).unwrap_or(&"sunny");
+
+ let weather_info = json!({
+ "location": location,
+ "temperature": temperature.to_string(),
+ "unit": unit,
+ "forecast": forecast
+ });
+
+ weather_info
+}
diff --git a/rust/cloud-storage/anthropic/examples/tools.rs b/rust/cloud-storage/anthropic/examples/tools.rs
new file mode 100644
index 0000000000..82dfa8af0d
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/tools.rs
@@ -0,0 +1,77 @@
+use anthropic::prelude::*;
+use futures::StreamExt;
+use serde_json::json;
+use std::io::Write;
+
+#[tokio::main]
+async fn main() {
+ // define tool (copy-pasted from openai playground)
+ let weather_tool = json!(
+
+ {
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "The city and state e.g. San Francisco, CA"
+ },
+ "unit": {
+ "type": "string",
+ "enum": [
+ "c",
+ "f"
+ ]
+ }
+ },
+ "additionalProperties": false,
+ "required": [
+ "location",
+ "unit"
+ ]
+ }
+ );
+
+ let client = anthropic::client::Client::dangerously_try_from_env();
+ let mut request = anthropic::types::request::CreateMessageRequestBody::default();
+ request.model = "claude-haiku-4-5".into();
+ request.max_tokens = 6767;
+ request.messages = vec![RequestMessage {
+ content: RequestContent::Text("what's the weather today in shenzen?".into()),
+ role: Role::User,
+ }];
+ request.tools = Some(vec![Tool {
+ description: Some("get the weather".into()),
+ name: "check_weather".into(),
+ input_schema: weather_tool,
+ }]);
+ let mut out = std::io::stdout();
+ let mut stream = client.chat().create_stream(request).await;
+ let mut tool_json = String::new();
+ while let Some(part) = stream.next().await {
+ if part.is_err() {
+ writeln!(out, "{:?}", part).expect("good ok yes");
+ break;
+ }
+ let part = part.unwrap();
+ match part {
+ StreamEvent::ContentBlockDelta { delta, .. } => match delta {
+ ContentDeltaEvent::InputJsonDelta { partial_json } => {
+ tool_json.push_str(&partial_json);
+ write!(out, "{}", partial_json).expect("ok good yes");
+ }
+ ContentDeltaEvent::TextDelta { text } => {
+ write!(out, "{}", text).expect("ok good yes");
+ }
+ other => {
+ writeln!(out, "{:?}", other).expect("donkey");
+ }
+ },
+ StreamEvent::ContentBlockStop { .. } | StreamEvent::ContentBlockStart { .. } => {
+ writeln!(out).expect("io")
+ }
+ event => writeln!(out, "{:?}", event).expect("io"),
+ }
+ }
+ let tool_call = serde_json::from_str::<serde_json::Value>(&tool_json);
+ println!("tool call {:#?}", tool_call);
+}
diff --git a/rust/cloud-storage/anthropic/examples/tools_openai.rs b/rust/cloud-storage/anthropic/examples/tools_openai.rs
new file mode 100644
index 0000000000..48cc7fedff
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/tools_openai.rs
@@ -0,0 +1,84 @@
+use anthropic::client::Client;
+use anthropic::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use async_openai::types::{
+ ChatCompletionRequestUserMessage, ChatCompletionRequestUserMessageContent,
+ ChatCompletionToolArgs, ChatCompletionToolType, CreateChatCompletionRequestArgs,
+ FunctionObjectArgs,
+};
+use futures::StreamExt;
+use serde_json::json;
+use std::io::Write;
+
+#[tokio::main]
+async fn main() {
+ let weather_tool = ChatCompletionToolArgs::default()
+ .r#type(ChatCompletionToolType::Function)
+ .function(
+ FunctionObjectArgs::default()
+ .name("get_current_weather")
+ .description("Get the current weather in a given location")
+ .parameters(json!({
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "The city and state, e.g. San Francisco, CA",
+ },
+ "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] },
+ },
+ "required": ["location"],
+ }))
+ .build()
+ .unwrap(),
+ )
+ .build()
+ .expect("tool");
+
+ let client = Client::dangerously_try_from_env();
+ let request = CreateChatCompletionRequestArgs::default()
+ .model("claude-haiku-4-5")
+ .max_completion_tokens(1000_u32)
+ .messages([ChatCompletionRequestUserMessage {
+ content: ChatCompletionRequestUserMessageContent::Text(
+ "what's the weather today in shenzhen?".into(),
+ ),
+ name: None,
+ }
+ .into()])
+ .tools(vec![weather_tool])
+ .build()
+ .expect("request");
+
+ let mut out = std::io::stdout();
+ let mut stream = client.chat().create_stream(request).await;
+ let mut tool_json = String::new();
+
+ while let Some(part) = stream.next().await {
+ writeln!(out, "{:#?}", part);
+ if part.is_err() {
+ writeln!(out, "{:?}", part).expect("io");
+ break;
+ }
+ let part = part.unwrap();
+ match part {
+ StreamEvent::ContentBlockStart { content_block, .. } => {}
+ StreamEvent::ContentBlockDelta { delta, .. } => match delta {
+ ContentDeltaEvent::InputJsonDelta { partial_json } => {
+ tool_json.push_str(&partial_json);
+ write!(out, "{}", partial_json).expect("ok good yes");
+ }
+ ContentDeltaEvent::TextDelta { text } => {
+ write!(out, "{}", text).expect("io");
+ }
+ other => writeln!(out, "{:?}", other).expect("io"),
+ },
+ StreamEvent::ContentBlockStop { .. } | StreamEvent::ContentBlockStart { .. } => {
+ writeln!(out).expect("io")
+ }
+ event => writeln!(out, "{:?}", event).expect("io"),
+ }
+ }
+
+ let tool_call = serde_json::from_str::<serde_json::Value>(&tool_json);
+ println!("tool call {:#?}", tool_call);
+}
diff --git a/rust/cloud-storage/anthropic/src/client/chat.rs b/rust/cloud-storage/anthropic/src/client/chat.rs
new file mode 100644
index 0000000000..caa6a72e4f
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/client/chat.rs
@@ -0,0 +1,45 @@
+use futures::Stream;
+use serde::{Serialize, de::DeserializeOwned};
+use std::fmt::Debug;
+use std::pin::Pin;
+
+use super::Client;
+use crate::error::AnthropicError;
+use crate::types::request::CreateMessageRequestBody;
+use crate::types::stream_response::StreamEvent;
+
+pub type MessageCompletionResponseStream =
+ Pin<Box<dyn Stream<Item = Result<StreamEvent, AnthropicError>> + Send>>;
+
+pub struct Chat<'c> {
+ pub(crate) inner: &'c Client,
+}
+
+impl Client {
+ pub fn chat(&'_ self) -> Chat<'_> {
+ Chat { inner: self }
+ }
+}
+
+impl<'c> Chat<'c> {
+ pub async fn create_stream<I>(&self, request: I) -> MessageCompletionResponseStream
+ where
+ I: Into<CreateMessageRequestBody>,
+ {
+ let mut request = request.into();
+ request.stream = Some(true);
+ self.create_stream_unchecked(request).await
+ }
+
+ pub async fn create_stream_unchecked<I, O>(
+ &self,
+ request: I,
+ ) -> Pin<Box<dyn Stream<Item = Result<O, AnthropicError>> + Send>>
+ where
+ I: Serialize + Debug,
+ O: DeserializeOwned + Send + Sync + 'static,
+ {
+ tracing::debug!("{:#?}", request);
+ self.inner.post_stream("/v1/messages", request).await
+ }
+}
diff --git a/rust/cloud-storage/anthropic/src/client/mod.rs b/rust/cloud-storage/anthropic/src/client/mod.rs
new file mode 100644
index 0000000000..7778612aa5
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/client/mod.rs
@@ -0,0 +1,109 @@
+pub mod chat;
+use crate::config::Config;
+use crate::error::AnthropicError;
+use futures::stream::{Stream, StreamExt};
+use reqwest::Client as RequestClient;
+use reqwest_eventsource::{Event, EventSource, RequestBuilderExt};
+use serde::{Serialize, de::DeserializeOwned};
+use std::pin::Pin;
+
+#[derive(Clone, Debug)]
+pub struct Client {
+ http_client: RequestClient,
+ config: Config,
+}
+
+impl Client {
+ pub fn dangerously_try_from_env() -> Self {
+ let config = Config::dangrously_try_from_env();
+ Self::with_config(config)
+ }
+}
+
+impl Client {
+ pub fn with_config(config: Config) -> Self {
+ let client = reqwest::Client::builder()
+ .default_headers(config.headers.clone())
+ .build()
+ .expect("reqwest client");
+ Self {
+ config,
+ http_client: client,
+ }
+ }
+
+ pub fn with_client(self, client: RequestClient) -> Self {
+ Self {
+ http_client: client,
+ ..self
+ }
+ }
+}
+
+impl Client {
+ pub(crate) async fn post_stream<I, O>(
+ &self,
+ path: &str,
+ request: I,
+ ) -> Pin<Box<dyn Stream<Item = Result<O, AnthropicError>> + Send>>
+ where
+ I: Serialize,
+ O: DeserializeOwned + Send + Sync + 'static,
+ {
+ let event_source = self
+ .http_client
+ .post(format!("{}{}", self.config.api_base, path))
+ .headers(self.config.headers.clone())
+ .json(&request)
+ .eventsource()
+ .expect("event source");
+
+ stream(event_source).await
+ }
+}
+
+async fn stream<O>(
+ mut event_source: EventSource,
+) -> Pin<Box<dyn Stream<Item = Result<O, AnthropicError>> + Send>>
+where
+ O: DeserializeOwned + std::marker::Send + 'static,
+{
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+
+ tokio::spawn(async move {
+ while let Some(ev) = event_source.next().await {
+ match ev {
+ Err(e) => {
+ match e {
+ reqwest_eventsource::Error::StreamEnded => break,
+ other => {
+ let _ = tx.send(Err(AnthropicError::StreamError(other.to_string())));
+ }
+ }
+ break;
+ }
+ Ok(event) => match event {
+ Event::Message(message) => {
+ if message.data == "[DONE]" {
+ break;
+ }
+
+ let response = match serde_json::from_str::<O>(&message.data) {
+ Err(e) => Err(AnthropicError::JsonDeserialize(e)),
+ Ok(output) => Ok(output),
+ };
+
+ if let Err(_e) = tx.send(response) {
+ // rx dropped
+ break;
+ }
+ }
+ Event::Open => continue,
+ },
+ }
+ }
+
+ event_source.close();
+ });
+ Box::pin(tokio_stream::wrappers::UnboundedReceiverStream::new(rx))
+}
diff --git a/rust/cloud-storage/anthropic/src/config.rs b/rust/cloud-storage/anthropic/src/config.rs
new file mode 100644
index 0000000000..b8b33d24b9
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/config.rs
@@ -0,0 +1,26 @@
+use reqwest::header::HeaderMap;
+
+const ANTHROPIC_ROUTER_BASE_URL: &str = "https://api.anthropic.com";
+const ANTHROPIC_API_KEY: &str = "ANTHROPIC_API_KEY";
+
+#[derive(Debug, Clone, Default)]
+pub struct Config {
+ pub api_base: String,
+ pub headers: HeaderMap,
+}
+
+impl Config {
+ pub fn dangrously_try_from_env() -> Self {
+ let api_key = std::env::var(ANTHROPIC_API_KEY).expect("api key");
+ let mut headers = HeaderMap::new();
+ headers.insert("x-api-key", api_key.parse().expect("good config"));
+ headers.insert(
+ "anthropic-version",
+ "2023-06-01".parse().expect("good version"),
+ );
+ Self {
+ api_base: ANTHROPIC_ROUTER_BASE_URL.into(),
+ headers,
+ }
+ }
+}
diff --git a/rust/cloud-storage/anthropic/src/error.rs b/rust/cloud-storage/anthropic/src/error.rs
new file mode 100644
index 0000000000..5cadf1f055
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/error.rs
@@ -0,0 +1,16 @@
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum AnthropicError {
+ /// An error sent by anthropic
+ #[error("Error returned from stream")]
+ StreamError(String),
+ /// Stream closed unexpectedly
+ #[error("Invalid json returned from stream")]
+ JsonDeserialize(serde_json::Error),
+ /// error from reqwest
+ #[error("http error")]
+ Reqwest(#[from] reqwest::Error),
+}
+
+pub type Result<T> = std::result::Result<T, AnthropicError>;
diff --git a/rust/cloud-storage/anthropic/src/lib.rs b/rust/cloud-storage/anthropic/src/lib.rs
new file mode 100644
index 0000000000..b505305bbb
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/lib.rs
@@ -0,0 +1,8 @@
+pub mod client;
+pub mod config;
+pub mod error;
+pub mod prelude;
+pub mod types;
+
+#[cfg(feature = "openai")]
+pub mod openai;
diff --git a/rust/cloud-storage/anthropic/src/openai/mod.rs b/rust/cloud-storage/anthropic/src/openai/mod.rs
new file mode 100644
index 0000000000..2ac38833e6
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/mod.rs
@@ -0,0 +1,2 @@
+pub mod request;
+pub mod stream_response;
diff --git a/rust/cloud-storage/anthropic/src/openai/request/conversions.rs b/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
new file mode 100644
index 0000000000..010032daed
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
@@ -0,0 +1,368 @@
+use crate::types::request::{self, SystemPrompt};
+use async_openai::types::{
+ ChatCompletionRequestAssistantMessage, ChatCompletionRequestDeveloperMessage,
+ ChatCompletionRequestFunctionMessage, ChatCompletionRequestMessage,
+ ChatCompletionRequestSystemMessage, ChatCompletionRequestSystemMessageContentPart,
+ ChatCompletionRequestToolMessage, ChatCompletionRequestUserMessage, ChatCompletionTool,
+ ChatCompletionToolChoiceOption, CreateChatCompletionRequest,
+};
+
+#[derive(Debug, Clone)]
+pub enum MessageConversionError {
+ /// System messages are not messages in anthropic api
+ SystemPrompt(ChatCompletionRequestSystemMessage),
+ /// Assistant messages may fail if all fields are None
+ MalformedAssistantMessage {
+ message: ChatCompletionRequestAssistantMessage,
+ reason: String,
+ },
+ /// Developer messages should be appended to the system prompt
+ DeveloperMessage(ChatCompletionRequestDeveloperMessage),
+ /// Function messges are deprecated / unsupported
+ FunctionMessage(ChatCompletionRequestFunctionMessage),
+}
+
+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),
+ ),
+ ..Default::default()
+ };
+
+ if let Some(user) = msg.metadata.and_then(|meta| {
+ meta.get("user_id")
+ .and_then(|user| user.as_str())
+ .map(|s| s.to_string())
+ }) {
+ request.metadata = Some(request::Metadata {
+ user_id: Some(user.to_owned()),
+ })
+ }
+ if let Some(stop_sequences) = msg.stop {
+ match stop_sequences {
+ async_openai::types::Stop::String(text) => {
+ request.stop_sequences = Some(vec![text])
+ }
+ async_openai::types::Stop::StringArray(parts) => {
+ request.stop_sequences = Some(parts)
+ }
+ }
+ }
+ request.model = msg.model;
+ request.stream = msg.stream;
+ request.temperature = msg.temperature;
+ request.tool_choice = msg.tool_choice.map(Into::into);
+ request.tools = msg
+ .tools
+ .map(|tools| tools.into_iter().map(Into::into).collect());
+ request.top_p = msg.top_p;
+
+ let mut prompt_messages = Vec::new();
+ let mut dev_messages = Vec::new();
+ let messages = msg.messages.into_iter().filter_map(|message| {
+ let ant_msg = request::RequestMessage::try_from(message);
+ if let Err(MessageConversionError::DeveloperMessage(dev_msg)) = ant_msg {
+ dev_messages.push(dev_msg);
+ None
+ } else if let Err(MessageConversionError::SystemPrompt(sys_msg)) = ant_msg {
+ prompt_messages.push(sys_msg);
+ None
+ } else {
+ ant_msg.ok()
+ }
+ });
+ request.messages = aggregate_messages(messages);
+ let mut system_prompt = SystemPrompt::from(prompt_messages);
+ for msg in dev_messages {
+ for text in developer_message_as_text_parts(&msg) {
+ system_prompt.push_text(text)
+ }
+ }
+ request.system = Some(system_prompt);
+ request
+ }
+}
+
+pub fn aggregate_messages(
+ messages: impl IntoIterator<Item = request::RequestMessage>,
+) -> Vec<request::RequestMessage> {
+ let mut result = Vec::new();
+ let mut accumulator: Option<request::RequestMessage> = None;
+ for current in messages {
+ match accumulator.take() {
+ None => {
+ accumulator = Some(current);
+ }
+ Some(acc) if acc.role == current.role => {
+ let acc = acc.merge_message(current);
+ accumulator = Some(acc);
+ }
+ Some(acc) => {
+ result.push(acc);
+ accumulator = Some(current);
+ }
+ }
+ }
+ if let Some(last) = accumulator {
+ result.push(last);
+ }
+ result
+}
+
+impl From<Vec<ChatCompletionRequestSystemMessage>> for request::SystemPrompt {
+ fn from(value: Vec<ChatCompletionRequestSystemMessage>) -> Self {
+ if value.is_empty() {
+ Self::Text(String::new())
+ } else if value.len() == 1 {
+ let parts = system_message_as_text_pars(&value[0]);
+ if parts.len() == 1 {
+ SystemPrompt::Text(parts[0].to_owned())
+ } else {
+ SystemPrompt::Blocks(
+ parts
+ .into_iter()
+ .map(|part| request::SystemContent {
+ r#type: "text".into(),
+ text: part.to_owned(),
+ cache_control: None,
+ citations: None,
+ })
+ .collect(),
+ )
+ }
+ } else {
+ let mut messages = Vec::new();
+ value.into_iter().for_each(|msg| {
+ let parts = system_message_as_text_pars(&msg);
+ let sys_parts = parts.into_iter().map(|part| request::SystemContent {
+ r#type: "text".into(),
+ text: part.to_owned(),
+ cache_control: None,
+ citations: None,
+ });
+ messages.extend(sys_parts);
+ });
+ SystemPrompt::Blocks(messages)
+ }
+ }
+}
+
+impl TryFrom<ChatCompletionRequestMessage> for request::RequestMessage {
+ type Error = MessageConversionError;
+ fn try_from(value: ChatCompletionRequestMessage) -> Result<Self, Self::Error> {
+ match value {
+ ChatCompletionRequestMessage::User(user_msg) => Ok(Self::from(user_msg)),
+ ChatCompletionRequestMessage::Assistant(assistant_msg) => Ok(Self::from(assistant_msg)),
+ ChatCompletionRequestMessage::Tool(tool_msg) => Ok(Self::from(tool_msg)),
+ ChatCompletionRequestMessage::System(prompt) => {
+ Err(MessageConversionError::SystemPrompt(prompt))
+ }
+ ChatCompletionRequestMessage::Developer(dev_msg) => {
+ Err(MessageConversionError::DeveloperMessage(dev_msg))
+ }
+ ChatCompletionRequestMessage::Function(function_msg) => {
+ Err(MessageConversionError::FunctionMessage(function_msg))
+ }
+ }
+ }
+}
+
+/// openai:tool_result_message -> anthropic:user_message
+impl From<ChatCompletionRequestToolMessage> for request::RequestMessage {
+ fn from(tool_msg: ChatCompletionRequestToolMessage) -> Self {
+ let tool = request::RequestContentKind::ToolResult {
+ tool_use_id: tool_msg.tool_call_id,
+ cache_control: None,
+ content: match tool_msg.content {
+ async_openai::types::ChatCompletionRequestToolMessageContent::Array(parts) => parts
+ .into_iter()
+ .map(|part| match part {
+ async_openai::types::ChatCompletionRequestToolMessageContentPart::Text(
+ text,
+ ) => text.text,
+ })
+ .collect::<String>(),
+ async_openai::types::ChatCompletionRequestToolMessageContent::Text(text) => text,
+ },
+ is_err: None,
+ };
+ Self {
+ role: request::Role::User,
+ content: request::RequestContent::Blocks(vec![tool]),
+ }
+ }
+}
+
+/// openai::user_msg -> anthropic::user_msg
+impl From<ChatCompletionRequestUserMessage> for request::RequestMessage {
+ fn from(user: ChatCompletionRequestUserMessage) -> Self {
+ match user.content {
+ async_openai::types::ChatCompletionRequestUserMessageContent::Array(arr) => {
+ let content: Vec<request::RequestContentKind> = arr.into_iter()
+ .filter_map(|part| {
+ match part {
+ async_openai::types::ChatCompletionRequestUserMessageContentPart::ImageUrl(url) => {
+ Some(if is_url(&url.image_url.url) {
+ request::RequestContentKind::Url { url: url.image_url.url }
+ } else {
+ let kind = media_type(&url.image_url.url);
+ request::RequestContentKind::Base64 { data: url.image_url.url, media_type: kind }
+ })
+ },
+ async_openai::types::ChatCompletionRequestUserMessageContentPart::Text(text) =>
+ Some(request::RequestContentKind::Text { text: text.text, cache_control: None, citations: vec![] }),
+ // sound is unsupported and will fail silently
+ async_openai::types::ChatCompletionRequestUserMessageContentPart::InputAudio(_) => None
+ }
+ })
+ .collect();
+ request::RequestMessage {
+ content: request::RequestContent::Blocks(content),
+ role: request::Role::User,
+ }
+ }
+ async_openai::types::ChatCompletionRequestUserMessageContent::Text(text) => Self {
+ role: request::Role::User,
+ content: request::RequestContent::Text(text),
+ },
+ }
+ }
+}
+
+/// openai::assistant_msg -> anthropci::assistant_msg
+impl From<ChatCompletionRequestAssistantMessage> for request::RequestMessage {
+ fn from(assistant_msg: ChatCompletionRequestAssistantMessage) -> Self {
+ let content = if let Some(content) = assistant_msg.content {
+ match content {
+ async_openai::types::ChatCompletionRequestAssistantMessageContent::Text(text) => {
+ request::RequestContent::Text(text)
+ }
+ async_openai::types::ChatCompletionRequestAssistantMessageContent::Array(parts) => {
+ let parts = parts.into_iter()
+ .map(|part| match part {
+ async_openai::types::ChatCompletionRequestAssistantMessageContentPart::Text(text) => {
+ request::RequestContentKind::Text { text: text.text, cache_control: None, citations: vec![]}
+ }
+ async_openai::types::ChatCompletionRequestAssistantMessageContentPart::Refusal(message) => {
+ request::RequestContentKind::Text { text: message.refusal, cache_control: None, citations: vec![] }
+ }
+
+ }).collect();
+
+ request::RequestContent::Blocks(parts)
+ }
+ }
+ } else {
+ request::RequestContent::Blocks(vec![])
+ };
+ let mut tools = if let Some(tools) = assistant_msg.tool_calls {
+ tools
+ .into_iter()
+ // TODO handle errors better
+ // anthropic requries tool calls to be valid json, openai doesn't
+ .filter_map(|tool_call| {
+ serde_json::from_str(&tool_call.function.arguments)
+ .map(|good| request::RequestContentKind::ToolUse {
+ id: tool_call.id,
+ input: good,
+ name: tool_call.function.name,
+ cache_control: None,
+ })
+ .ok()
+ })
+ .collect()
+ } else {
+ vec![]
+ };
+ match (tools.is_empty(), content) {
+ (true, content) => request::RequestMessage {
+ content,
+ role: request::Role::Assistant,
+ },
+ (_, request::RequestContent::Blocks(mut b)) => {
+ b.append(&mut tools);
+ request::RequestMessage {
+ content: request::RequestContent::Blocks(b),
+ role: request::Role::Assistant,
+ }
+ }
+ (_, request::RequestContent::Text(t)) => {
+ let mut content = vec![request::RequestContentKind::Text {
+ text: t,
+ cache_control: None,
+ citations: vec![],
+ }];
+ content.append(&mut tools);
+ request::RequestMessage {
+ content: request::RequestContent::Blocks(content),
+ role: request::Role::Assistant,
+ }
+ }
+ }
+ }
+}
+
+impl From<ChatCompletionToolChoiceOption> for request::ToolChoice {
+ fn from(value: ChatCompletionToolChoiceOption) -> Self {
+ match value {
+ ChatCompletionToolChoiceOption::Auto => Self::Auto {
+ disable_parallel_tool_use: false,
+ },
+ ChatCompletionToolChoiceOption::Named(named) => Self::Tool {
+ name: named.function.name,
+ disable_parallel_tool_use: false,
+ },
+ ChatCompletionToolChoiceOption::None => Self::None,
+ ChatCompletionToolChoiceOption::Required => Self::Any {
+ disable_parallel_tool_use: false,
+ },
+ }
+ }
+}
+
+impl From<ChatCompletionTool> for request::Tool {
+ fn from(value: ChatCompletionTool) -> Self {
+ Self {
+ description: value.function.description,
+ input_schema: value.function.parameters.unwrap_or_default(),
+ name: value.function.name,
+ }
+ }
+}
+
+fn system_message_as_text_pars(sys_msg: &ChatCompletionRequestSystemMessage) -> Vec<&str> {
+ match sys_msg.content {
+ async_openai::types::ChatCompletionRequestSystemMessageContent::Array(ref parts) => parts
+ .iter()
+ .map(|part| match part {
+ ChatCompletionRequestSystemMessageContentPart::Text(text) => text.text.as_str(),
+ })
+ .collect(),
+ async_openai::types::ChatCompletionRequestSystemMessageContent::Text(ref text) => {
+ vec![text.as_str()]
+ }
+ }
+}
+
+fn developer_message_as_text_parts(dev_msg: &ChatCompletionRequestDeveloperMessage) -> Vec<&str> {
+ match dev_msg.content {
+ async_openai::types::ChatCompletionRequestDeveloperMessageContent::Array(ref parts) => {
+ parts.iter().map(|part| part.text.as_str()).collect()
+ }
+ async_openai::types::ChatCompletionRequestDeveloperMessageContent::Text(ref t) => vec![t],
+ }
+}
+
+fn is_url(s: &str) -> bool {
+ s.starts_with("http")
+}
+
+fn media_type(b64: &str) -> String {
+ b64.strip_prefix("data:")
+ .and_then(|d| d.split(';').next())
+ .map(|s| s.to_owned())
+ .unwrap_or_else(|| "image/png".into())
+}
diff --git a/rust/cloud-storage/anthropic/src/openai/request/mod.rs b/rust/cloud-storage/anthropic/src/openai/request/mod.rs
new file mode 100644
index 0000000000..a29ed27628
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/request/mod.rs
@@ -0,0 +1,5 @@
+mod conversions;
+pub use conversions::*;
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/anthropic/src/openai/request/test.rs b/rust/cloud-storage/anthropic/src/openai/request/test.rs
new file mode 100644
index 0000000000..0f8ee65d06
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/request/test.rs
@@ -0,0 +1,277 @@
+use crate::types::request::*;
+use async_openai::types::CreateChatCompletionRequest;
+
+fn failed_tool_calls() -> CreateChatCompletionRequest {
+ let request = r#"
+ {
+ "messages": [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "<system_prompt>"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "content": "greetings clanker. list my documents"
+ },
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": "toolu_019UNdEieCsVUEiHXaKgooMM",
+ "type": "function",
+ "function": {
+ "name": "ListDocuments",
+ "arguments": "{\"exhaustiveSearch\":true,\"fileTypes\":[],\"minAccessLevel\":null,\"pageOffset\":0,\"pageSize\":100}"
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "content": "failed to list documents: HTTP 400 Bad Request: Invalid URL: missing field `document_id`",
+ "tool_call_id": "toolu_019UNdEieCsVUEiHXaKgooMM"
+ },
+ {
+ "role": "assistant",
+ "content": "Let me try that again with the proper parameters:",
+ "tool_calls": [
+ {
+ "id": "toolu_013zTT5ZpforGBtoi3bn2C74",
+ "type": "function",
+ "function": {
+ "name": "ListDocuments",
+ "arguments": "{\"exhaustiveSearch\":true,\"fileTypes\":[],\"minAccessLevel\":\"view\",\"pageOffset\":0,\"pageSize\":100}"
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "content": "failed to list documents: HTTP 400 Bad Request: Invalid URL: missing field `document_id`",
+ "tool_call_id": "toolu_013zTT5ZpforGBtoi3bn2C74"
+ }
+ ],
+ "model": "claude-haiku-4-5",
+ "reasoning_effort": "medium",
+ "stream": true,
+ "stream_options": {
+ "include_usage": true
+ },
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "ListDocuments",
+ "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "parameters": {
+ "additionalProperties": false,
+ "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "properties": {
+ "exhaustiveSearch": {
+ "additionalProperties": false,
+ "default": false,
+ "description": "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.",
+ "type": "boolean"
+ },
+ "fileTypes": {
+ "additionalProperties": false,
+ "description": "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": [
+ "array",
+ "null"
+ ]
+ },
+ "minAccessLevel": {
+ "additionalProperties": false,
+ "description": "Minimum access level required. Defaults to 'view' if not specified.",
+ "enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner",
+ null
+ ],
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "pageOffset": {
+ "additionalProperties": false,
+ "default": 0,
+ "description": "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.",
+ "format": "int64",
+ "type": "integer"
+ },
+ "pageSize": {
+ "additionalProperties": false,
+ "default": 50,
+ "description": "Number of results per page. Max is 100, default is 50. Use smaller values for focused results.",
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "exhaustiveSearch",
+ "fileTypes",
+ "minAccessLevel",
+ "pageOffset",
+ "pageSize"
+ ],
+ "title": "ListDocuments",
+ "type": "object"
+ },
+ "strict": true
+ }
+ }
+ ]
+ }
+ "#;
+ serde_json::from_str(request).expect("good request")
+}
+
+fn expected_failed_tool_calls() -> CreateMessageRequestBody {
+ CreateMessageRequestBody {
+ model: "claude-haiku-4-5".into(),
+ messages: vec![
+ RequestMessage {
+ role: Role::User,
+ content: RequestContent::Text("greetings clanker. list my documents".into()),
+ },
+ RequestMessage {
+ role: Role::Assistant,
+ content: RequestContent::Blocks(vec![RequestContentKind::ToolUse {
+ id: "toolu_019UNdEieCsVUEiHXaKgooMM".into(),
+ name: "ListDocuments".into(),
+ input: serde_json::json!({
+ "exhaustiveSearch": true,
+ "fileTypes": [],
+ "minAccessLevel": null,
+ "pageOffset": 0,
+ "pageSize": 100
+ }),
+ cache_control: None,
+ }]),
+ },
+ RequestMessage {
+ role: Role::User,
+ content: RequestContent::Blocks(vec![RequestContentKind::ToolResult {
+ tool_use_id: "toolu_019UNdEieCsVUEiHXaKgooMM".into(),
+ content: "failed to list documents: HTTP 400 Bad Request: Invalid URL: missing field `document_id`".into(),
+ is_err: None,
+ cache_control: None,
+ }]),
+ },
+ RequestMessage {
+ role: Role::Assistant,
+ content: RequestContent::Blocks(vec![
+ RequestContentKind::Text {
+ text: "Let me try that again with the proper parameters:".into(),
+ cache_control: None,
+ citations: vec![],
+ },
+ RequestContentKind::ToolUse {
+ id: "toolu_013zTT5ZpforGBtoi3bn2C74".into(),
+ name: "ListDocuments".into(),
+ input: serde_json::json!({
+ "exhaustiveSearch": true,
+ "fileTypes": [],
+ "minAccessLevel": "view",
+ "pageOffset": 0,
+ "pageSize": 100
+ }),
+ cache_control: None,
+ },
+ ]),
+ },
+ RequestMessage {
+ role: Role::User,
+ content: RequestContent::Blocks(vec![RequestContentKind::ToolResult {
+ tool_use_id: "toolu_013zTT5ZpforGBtoi3bn2C74".into(),
+ content: "failed to list documents: HTTP 400 Bad Request: Invalid URL: missing field `document_id`".into(),
+ is_err: None,
+ cache_control: None,
+ }]),
+ },
+ ],
+ max_tokens: 32_000,
+ container: None,
+ context_management: None,
+ mcp_servers: None,
+ metadata: None,
+ service_tier: None,
+ stop_sequences: None,
+ stream: Some(true),
+ system: Some(SystemPrompt::Text("<system_prompt>".into())),
+ temperature: None,
+ thinking: None,
+ tool_choice: None,
+ tools: Some(vec![Tool {
+ name: "ListDocuments".into(),
+ description: Some("List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.".into()),
+ input_schema: serde_json::json!({
+ "additionalProperties": false,
+ "description": "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",
+ "properties": {
+ "exhaustiveSearch": {
+ "additionalProperties": false,
+ "default": false,
+ "description": "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.",
+ "type": "boolean"
+ },
+ "fileTypes": {
+ "additionalProperties": false,
+ "description": "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.",
+ "items": {
+ "additionalProperties": false,
+ "type": "string"
+ },
+ "type": ["array", "null"]
+ },
+ "minAccessLevel": {
+ "additionalProperties": false,
+ "description": "Minimum access level required. Defaults to 'view' if not specified.",
+ "enum": ["view", "comment", "edit", "owner", null],
+ "type": ["string", "null"]
+ },
+ "pageOffset": {
+ "additionalProperties": false,
+ "default": 0,
+ "description": "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.",
+ "format": "int64",
+ "type": "integer"
+ },
+ "pageSize": {
+ "additionalProperties": false,
+ "default": 50,
+ "description": "Number of results per page. Max is 100, default is 50. Use smaller values for focused results.",
+ "format": "int64",
+ "type": "integer"
+ }
+ },
+ "required": ["exhaustiveSearch", "fileTypes", "minAccessLevel", "pageOffset", "pageSize"],
+ "title": "ListDocuments",
+ "type": "object"
+ })
+ }]),
+ top_k: None,
+ top_p: None,
+ }
+}
+
+#[test]
+fn test_conversion() {
+ let oai_request = failed_tool_calls();
+ let expected = expected_failed_tool_calls();
+ let converted = CreateMessageRequestBody::from(oai_request);
+ assert_eq!(converted, expected);
+}
diff --git a/rust/cloud-storage/anthropic/src/openai/stream_response.rs b/rust/cloud-storage/anthropic/src/openai/stream_response.rs
new file mode 100644
index 0000000000..7a846069e8
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/stream_response.rs
@@ -0,0 +1,294 @@
+use crate::client::chat::MessageCompletionResponseStream;
+use crate::error::AnthropicError;
+use crate::types::response::StopReason;
+use crate::types::response::Usage;
+use crate::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use crate::{client::chat::Chat, prelude::CreateMessageRequestBody};
+use async_openai::error::{ApiError, OpenAIError};
+use async_openai::types::{
+ ChatChoiceStream, ChatCompletionMessageToolCallChunk, ChatCompletionResponseStream,
+ ChatCompletionStreamResponseDelta, ChatCompletionToolType, CreateChatCompletionStreamResponse,
+ FinishReason, FunctionCallStream, Role,
+};
+use async_stream::stream;
+use futures::StreamExt;
+use serde::Serialize;
+
+// Helper functions to create stream responses
+fn create_response(
+ message_id: &str,
+ model: &str,
+ created: u32,
+ index: u32,
+ delta: ChatCompletionStreamResponseDelta,
+ finish_reason: Option<FinishReason>,
+ usage: Option<async_openai::types::CompletionUsage>,
+) -> CreateChatCompletionStreamResponse {
+ CreateChatCompletionStreamResponse {
+ id: message_id.to_string(),
+ choices: vec![ChatChoiceStream {
+ index,
+ delta,
+ finish_reason,
+ logprobs: None,
+ }],
+ created,
+ model: model.to_string(),
+ system_fingerprint: None,
+ object: "chat.completion.chunk".to_string(),
+ service_tier: None,
+ usage,
+ }
+}
+
+fn create_role_delta(role: Role) -> ChatCompletionStreamResponseDelta {
+ ChatCompletionStreamResponseDelta {
+ role: Some(role),
+ content: None,
+ tool_calls: None,
+ #[allow(deprecated)]
+ function_call: None,
+ refusal: None,
+ }
+}
+
+fn create_content_delta(content: String) -> ChatCompletionStreamResponseDelta {
+ ChatCompletionStreamResponseDelta {
+ role: None,
+ content: Some(content),
+ tool_calls: None,
+ #[allow(deprecated)]
+ function_call: None,
+ refusal: None,
+ }
+}
+
+fn create_tool_call_delta(
+ index: u32,
+ id: Option<String>,
+ type_: Option<ChatCompletionToolType>,
+ name: Option<String>,
+ arguments: Option<String>,
+) -> ChatCompletionStreamResponseDelta {
+ ChatCompletionStreamResponseDelta {
+ role: None,
+ content: None,
+ tool_calls: Some(vec![ChatCompletionMessageToolCallChunk {
+ index,
+ id,
+ r#type: type_,
+ function: Some(FunctionCallStream { name, arguments }),
+ }]),
+ #[allow(deprecated)]
+ function_call: None,
+ refusal: None,
+ }
+}
+
+fn create_empty_delta() -> ChatCompletionStreamResponseDelta {
+ ChatCompletionStreamResponseDelta {
+ role: None,
+ content: None,
+ tool_calls: None,
+ #[allow(deprecated)]
+ function_call: None,
+ refusal: None,
+ }
+}
+
+fn map_stop_reason(stop_reason: StopReason) -> FinishReason {
+ match stop_reason {
+ StopReason::EndTurn => FinishReason::Stop,
+ StopReason::MaxTokens => FinishReason::Length,
+ StopReason::StopSequence => FinishReason::Stop,
+ StopReason::ToolUse => FinishReason::ToolCalls,
+ StopReason::PausTurn => FinishReason::Stop,
+ StopReason::Refusal => FinishReason::ContentFilter,
+ }
+}
+
+pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletionResponseStream {
+ Box::pin(stream! {
+ let mut message_id: Option<String> = None;
+ let mut model: Option<String> = None;
+ let created = chrono::Utc::now().timestamp();
+ let mut streaming_tool_name = String::new();
+ let mut streaming_tool_id = String::new();
+
+ while let Some(part) = stream.next().await {
+ let result = if let Err(e) = part {
+ Err(match e {
+ AnthropicError::JsonDeserialize(e) => OpenAIError::JSONDeserialize(e),
+ AnthropicError::Reqwest(e) => OpenAIError::Reqwest(e),
+ AnthropicError::StreamError(e) => OpenAIError::StreamError(e),
+ })
+ } else {
+ match part.unwrap() {
+ StreamEvent::MessageStart { message } => {
+ message_id = message.id.clone();
+ model = message.model.clone();
+
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ 0,
+ create_role_delta(Role::Assistant),
+ None,
+ None,
+ ))
+ }
+ StreamEvent::ContentBlockStart { content_block, ..} => {
+ if let ContentDeltaEvent::ToolUse { name, id, .. } = content_block {
+ streaming_tool_name = name;
+ streaming_tool_id = id;
+ }
+ // Skip content block start events
+ continue;
+ }
+ StreamEvent::ContentBlockDelta { index, delta } => {
+ match delta {
+ ContentDeltaEvent::TextDelta { text } | ContentDeltaEvent::StartTextDelta { text } => {
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ index,
+ create_content_delta(text),
+ None,
+ None,
+ ))
+ }
+ ContentDeltaEvent::ThinkingDelta { thinking } => {
+ // OpenAI doesn't have thinking blocks, skip or include as content
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ index,
+ create_content_delta(format!("[Thinking] {}", thinking)),
+ None,
+ None,
+ ))
+ }
+ ContentDeltaEvent::ToolUse { id, name, input } => {
+ // Map to OpenAI tool call
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ index,
+ create_tool_call_delta(
+ index,
+ Some(id),
+ Some(ChatCompletionToolType::Function),
+ Some(name),
+ Some(input.to_string()),
+ ),
+ None,
+ None,
+ ))
+ }
+ ContentDeltaEvent::InputJsonDelta { partial_json } => {
+ // Stream partial JSON for tool call arguments
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ index,
+ create_tool_call_delta(
+ index,
+ Some(streaming_tool_id.clone()),
+ None,
+ Some(streaming_tool_name.clone()),
+ Some(partial_json),
+ ),
+ None,
+ None,
+ ))
+ }
+ ContentDeltaEvent::SignatureDelta { .. } => {
+ // Skip signature deltas as OpenAI doesn't have an equivalent
+ continue;
+ }
+ }
+ }
+ StreamEvent::ContentBlockStop { .. } => {
+ // Skip content block stop events
+ continue;
+ }
+ StreamEvent::MessageDelta { delta , usage } => {
+ let finish_reason = delta.stop_reason.map(map_stop_reason);
+
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ 0,
+ create_empty_delta(),
+ finish_reason,
+ usage.map(Into::into),
+ ))
+ }
+ StreamEvent::MessageStop => {
+ Ok(create_response(
+ &message_id.clone().unwrap_or_default(),
+ &model.clone().unwrap_or_default(),
+ created as u32,
+ 0,
+ create_empty_delta(),
+ Some(FinishReason::Stop),
+ None,
+ ))
+ }
+ StreamEvent::Ping => {
+ // Skip ping events
+ continue;
+ }
+ StreamEvent::Error { error } => {
+ Err(OpenAIError::ApiError(ApiError {
+ message: format!("{:?}", error),
+ r#type: None,
+ param: None,
+ code: None,
+ }))
+ }
+ }
+ };
+ yield result;
+ }
+ })
+}
+
+impl From<Usage> for async_openai::types::CompletionUsage {
+ fn from(value: Usage) -> async_openai::types::CompletionUsage {
+ Self {
+ prompt_tokens: value.input_tokens,
+ completion_tokens: value.output_tokens,
+ total_tokens: value.input_tokens + value.output_tokens,
+ prompt_tokens_details: None,
+ completion_tokens_details: None,
+ }
+ }
+}
+
+impl<'c> Chat<'c> {
+ pub async fn create_stream_openai<I>(&self, request: I) -> ChatCompletionResponseStream
+ where
+ I: Into<CreateMessageRequestBody>,
+ {
+ let mut request = request.into();
+ request.stream = Some(true);
+ self.create_stream_openai_unchecked(request).await
+ }
+
+ pub async fn create_stream_openai_unchecked<I>(
+ &self,
+ request: I,
+ ) -> ChatCompletionResponseStream
+ where
+ I: Serialize,
+ {
+ map_stream(self.inner.post_stream("/v1/messages", request).await)
+ }
+}
diff --git a/rust/cloud-storage/anthropic/src/prelude.rs b/rust/cloud-storage/anthropic/src/prelude.rs
new file mode 100644
index 0000000000..fa22d0d1fd
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/prelude.rs
@@ -0,0 +1,8 @@
+pub use crate::client::*;
+pub use crate::config::*;
+pub use crate::types::request::*;
+pub use crate::types::response::*;
+pub use crate::types::stream_response::*;
+
+#[cfg(feature = "openai")]
+pub use crate::openai::*;
diff --git a/rust/cloud-storage/anthropic/src/types/mod.rs b/rust/cloud-storage/anthropic/src/types/mod.rs
new file mode 100644
index 0000000000..fcb205c8f5
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/mod.rs
@@ -0,0 +1,4 @@
+pub mod request;
+pub mod request_util;
+pub mod response;
+pub mod stream_response;
diff --git a/rust/cloud-storage/anthropic/src/types/request.rs b/rust/cloud-storage/anthropic/src/types/request.rs
new file mode 100644
index 0000000000..57a0bc4afc
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/request.rs
@@ -0,0 +1,193 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Copy)]
+#[serde(rename_all = "lowercase")]
+pub enum Role {
+ Assistant,
+ User,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(untagged, rename_all = "lowercase")]
+pub enum RequestContent {
+ Text(String),
+ Blocks(Vec<RequestContentKind>),
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum RequestContentKind {
+ Text {
+ text: String,
+ cache_control: Option<CacheControl>,
+ // TODO?
+ citations: Vec<serde_json::Value>,
+ },
+ Base64 {
+ data: String,
+ /// one of image/jpeg | image/png | image/gif | image/webp
+ media_type: String,
+ },
+ Url {
+ url: String,
+ },
+ ToolUse {
+ id: String,
+ input: serde_json::Value,
+ name: String,
+ cache_control: Option<CacheControl>,
+ },
+ ToolResult {
+ tool_use_id: String,
+ // his accepts more complete content input https://docs.claude.com/en/api/messages#tool-result
+ content: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cache_control: Option<CacheControl>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ is_err: Option<bool>,
+ },
+}
+
+// who cares https://docs.claude.com/en/api/messages#tool-result
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct CacheControl(serde_json::Value);
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct RequestMessage {
+ pub role: Role,
+ pub content: RequestContent,
+}
+
+// unused
+#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
+pub struct McpServer;
+
+#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
+pub struct Metadata {
+ /// An external identifier for the user who is associated with the request.
+ pub user_id: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum ServiceTier {
+ #[default]
+ Auto,
+ StandardOnly,
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
+#[serde(untagged)]
+pub enum SystemPrompt {
+ Blocks(Vec<SystemContent>),
+ Text(String),
+}
+
+impl Default for SystemPrompt {
+ fn default() -> Self {
+ SystemPrompt::Text("".into())
+ }
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
+pub struct SystemContent {
+ /// type: "text"
+ pub r#type: String,
+ pub text: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cache_control: Option<CacheControl>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub citations: Option<serde_json::Value>,
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
+#[serde(rename_all = "lowercase", tag = "type")]
+pub enum Thinking {
+ Enabled {
+ budget_tokens: u32,
+ },
+ #[default]
+ Disabled,
+}
+
+#[derive(Default, Serialize, Deserialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "lowercase", tag = "type")]
+pub enum ToolChoice {
+ Auto {
+ disable_parallel_tool_use: bool,
+ },
+ Any {
+ disable_parallel_tool_use: bool,
+ },
+ Tool {
+ name: String,
+ disable_parallel_tool_use: bool,
+ },
+ #[default]
+ None,
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
+pub struct Tool {
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+ pub input_schema: serde_json::Value,
+}
+
+#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct CreateMessageRequestBody {
+ /// The model that will complete your prompt.
+ /// https://docs.claude.com/en/docs/about-claude/models/overview
+ pub model: String,
+ /// Input messages.
+ pub messages: Vec<RequestMessage>,
+ /// The maximum number of tokens to generate before stopping.
+ pub max_tokens: u32,
+ /// !Not Implemented!
+ /// Container identifier for reuse across requests.
+ /// Container parameters with skills to be loaded.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub container: Option<String>,
+ /// !Not Implemented!
+ /// Context management configuration.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub context_management: Option<String>,
+ /// !Not Implemented!
+ /// MCP servers to be utilized in this request
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mcp_servers: Option<Vec<McpServer>>,
+ /// An object describing metadata about the request.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub metadata: Option<Metadata>,
+ /// Determines whether to use priority capacity (if available) or standard capacity for this request.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub service_tier: Option<ServiceTier>,
+ /// Custom text sequences that will cause the model to stop generating.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub stop_sequences: Option<Vec<String>>,
+ /// Whether to incrementally stream the response using server-sent events.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub stream: Option<bool>,
+ /// System prompt.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub system: Option<SystemPrompt>,
+ /// Amount of randomness injected into the response.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub temperature: Option<f32>,
+ /// Configuration for enabling Claude's extended thinking.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub thinking: Option<Thinking>,
+ /// How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tool_choice: Option<ToolChoice>,
+ /// Definitions of tools that the model may use.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tools: Option<Vec<Tool>>,
+ /// Only sample from the top K options for each subsequent token.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub top_k: Option<u32>,
+ /// Use nucleus sampling.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub top_p: Option<f32>,
+}
diff --git a/rust/cloud-storage/anthropic/src/types/request_util.rs b/rust/cloud-storage/anthropic/src/types/request_util.rs
new file mode 100644
index 0000000000..d3d9ae14ce
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/request_util.rs
@@ -0,0 +1,58 @@
+use super::request::*;
+
+impl RequestContentKind {
+ pub fn text(text: String) -> Self {
+ Self::Text {
+ text,
+ cache_control: None,
+ citations: vec![],
+ }
+ }
+}
+
+impl SystemPrompt {
+ pub fn push_text(&mut self, text: &str) {
+ match self {
+ Self::Blocks(parts) => {
+ parts.push(SystemContent {
+ r#type: "text".into(),
+ text: text.to_owned(),
+ cache_control: None,
+ citations: None,
+ });
+ }
+ Self::Text(prompt) => {
+ prompt.push_str(text);
+ }
+ }
+ }
+}
+
+impl RequestMessage {
+ pub fn merge_message(self, other: Self) -> Self {
+ match (self.content, other.content) {
+ (RequestContent::Text(t), b) => Self {
+ role: self.role,
+ content: RequestContent::Blocks(vec![RequestContentKind::text(t)]),
+ }
+ .merge_message(Self {
+ role: other.role,
+ content: b,
+ }),
+ (RequestContent::Blocks(mut a), RequestContent::Blocks(mut b)) => {
+ a.append(&mut b);
+ Self {
+ role: self.role,
+ content: RequestContent::Blocks(a),
+ }
+ }
+ (RequestContent::Blocks(mut a), RequestContent::Text(t)) => {
+ a.push(RequestContentKind::text(t));
+ Self {
+ role: self.role,
+ content: RequestContent::Blocks(a),
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/anthropic/src/types/response.rs b/rust/cloud-storage/anthropic/src/types/response.rs
new file mode 100644
index 0000000000..15587c2ee2
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/response.rs
@@ -0,0 +1,105 @@
+use super::request::Role;
+use serde::{Deserialize, Serialize};
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ResponseContentKind {
+ Text(TextResponse),
+ Thinking(ThinkingResponse),
+ ToolUse(ToolUse),
+ // there are many more options that could be implemented here
+ // https://docs.claude.com/en/api/messages#responsewebfetchtoolresultblock
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(rename_all = "snake_case", untagged)]
+pub enum Content {
+ Text(String),
+ Array(Vec<ResponseContentKind>),
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct WebSearchToolResult {
+ pub content: serde_json::Value,
+ pub tool_use_id: String,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct ServerToolUse {
+ pub id: String,
+ pub input: serde_json::Value,
+ // one of web_search | web_fetch | code_execution | bash_code_execution | text_editor_code_execution
+ pub name: String,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct ToolUse {
+ pub id: String,
+ pub input: serde_json::Value,
+ pub name: String,
+}
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct ThinkingResponse {
+ pub signature: String,
+ pub thinking: String,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct RedactedThinking {
+ pub data: String,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct TextResponse {
+ citations: Vec<serde_json::Value>,
+ text: String,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum StopReason {
+ EndTurn,
+ MaxTokens,
+ StopSequence,
+ ToolUse,
+ PausTurn,
+ Refusal,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct Usage {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cache_creation: Option<serde_json::Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cache_creation_input_tokens: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cache_read_input_tokens: Option<u32>,
+ pub input_tokens: u32,
+ pub output_tokens: u32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub server_tool_use: Option<serde_json::Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub service_tier: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct MessageResponse {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub r#type: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub role: Option<Role>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content: Option<Content>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub model: Option<String>,
+ pub stop_reason: Option<StopReason>,
+ pub stop_sequence: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub usage: Option<Usage>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub context_management: Option<serde_json::Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub container: Option<serde_json::Value>,
+}
diff --git a/rust/cloud-storage/anthropic/src/types/stream_response.rs b/rust/cloud-storage/anthropic/src/types/stream_response.rs
new file mode 100644
index 0000000000..d015ad4d2f
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/stream_response.rs
@@ -0,0 +1,425 @@
+use super::response::MessageResponse;
+use super::response::Usage;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum StreamEvent {
+ MessageStart {
+ message: MessageResponse,
+ },
+ /// proceeds content block delta
+ ContentBlockStart {
+ index: u32,
+ content_block: ContentDeltaEvent,
+ },
+ ContentBlockDelta {
+ index: u32,
+ delta: ContentDeltaEvent,
+ },
+ /// follows content block delta
+ ContentBlockStop {
+ index: u32,
+ },
+ MessageDelta {
+ delta: MessageResponse,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ usage: Option<Usage>,
+ }, // changes to top level message
+ Error {
+ error: StreamError,
+ },
+ MessageStop,
+ Ping,
+}
+
+// data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01T1x1fJ34qAmk2tNTrN7Up6","name":"get_weather","input":{}}}
+// https://docs.claude.com/en/docs/build-with-claude/streaming#full-http-stream-response
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ContentDeltaEvent {
+ #[serde(rename = "text")]
+ StartTextDelta {
+ text: String,
+ },
+ TextDelta {
+ text: String,
+ },
+ /// proceeds input json dleta
+ ToolUse {
+ id: String,
+ name: String,
+ input: serde_json::Value,
+ },
+ /// partial json for a tool call
+ InputJsonDelta {
+ partial_json: String,
+ },
+ ThinkingDelta {
+ thinking: String,
+ },
+ SignatureDelta {
+ signature: String,
+ },
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum StreamError {
+ OverloadedError { message: String },
+ OtherError { message: String },
+}
+
+#[cfg(test)]
+mod test {
+ use serde_json::{Value, json};
+
+ use super::*;
+ use crate::types::request::*;
+ use crate::types::response::*;
+
+ fn error() -> Value {
+ json!(
+ {"error": {"type": "overloaded_error", "message": "Overloaded"}, "type": "error"}
+ )
+ }
+
+ fn start() -> Value {
+ json!({
+ "type":"message_start",
+ "message":{
+ "id":"abc",
+ "type":"message",
+ "role":"assistant",
+ "model":"claude-sonnet-4-5-20250929",
+ "stop_sequence":null,
+ "usage": {"input_tokens":472,"output_tokens":2},
+ "content":[],
+ "stop_reason":null}})
+ }
+
+ fn content_block_start_text() -> Value {
+ json!({"type":"content_block_start","index":0,"content_block":{"type":"text_delta","text":""}})
+ }
+
+ fn content_block_start_tool_use() -> Value {
+ json!({"type":"content_block_start","index":1,"content_block":{"type":"input_json_delta","partial_json":""}})
+ }
+
+ fn content_block_delta_text() -> Value {
+ json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}})
+ }
+
+ fn content_block_delta_json() -> Value {
+ json!({"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"location\":\""}})
+ }
+
+ fn content_block_stop() -> Value {
+ json!({"type":"content_block_stop","index":0})
+ }
+
+ fn message_delta() -> Value {
+ json!({
+ "type":"message_delta",
+ "delta": {
+ "id":"abc",
+ "type":"message",
+ "role":"assistant",
+ "model":"claude-sonnet-4-5-20250929",
+ "stop_sequence":null,
+ "usage": {
+ "input_tokens":472,
+ "output_tokens":2},
+ "content":[],
+ "stop_reason":null
+ }
+ })
+ }
+
+ fn message_stop() -> Value {
+ json!({"type":"message_stop"})
+ }
+
+ fn ping() -> Value {
+ json!({"type":"ping"})
+ }
+
+ #[test]
+ fn test_se_start() {
+ let se = serde_json::to_value(&StreamEvent::MessageStart {
+ message: MessageResponse {
+ r#type: Some("message".into()),
+ id: Some("abc".into()),
+ container: None,
+ content: Some(Content::Array(vec![])),
+ role: Some(Role::Assistant),
+ context_management: None,
+ model: Some("claude-sonnet-4-5-20250929".into()),
+ stop_sequence: None,
+ stop_reason: None,
+ usage: Some(Usage {
+ cache_creation: None,
+ cache_creation_input_tokens: None,
+ cache_read_input_tokens: None,
+ input_tokens: 472,
+ output_tokens: 2,
+ server_tool_use: None,
+ service_tier: None,
+ }),
+ },
+ })
+ .expect("se start");
+ assert_eq!(se, start(), "start");
+ }
+
+ #[test]
+ fn test_se_err() {
+ let se = serde_json::to_value(StreamEvent::Error {
+ error: StreamError::OverloadedError {
+ message: "Overloaded".into(),
+ },
+ })
+ .expect("se str");
+
+ assert_eq!(se, error(), "serialize error")
+ }
+
+ #[test]
+ fn test_de_start() {
+ let de =
+ serde_json::from_str::<StreamEvent>(&serde_json::to_string(&start()).expect("str"))
+ .expect("deserialize_start");
+ assert!(
+ if let StreamEvent::MessageStart { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize start"
+ );
+ }
+
+ #[test]
+ fn test_se_content_block_start_text() {
+ let se = serde_json::to_value(&StreamEvent::ContentBlockStart {
+ index: 0,
+ content_block: ContentDeltaEvent::TextDelta { text: "".into() },
+ })
+ .expect("se content_block_start_text");
+ assert_eq!(se, content_block_start_text(), "content_block_start_text");
+ }
+
+ #[test]
+ fn test_de_content_block_start_text() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&content_block_start_text()).expect("str"),
+ )
+ .expect("deserialize_content_block_start_text");
+ assert!(
+ if let StreamEvent::ContentBlockStart { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize content_block_start_text"
+ );
+ }
+
+ #[test]
+ fn test_se_content_block_start_tool_use() {
+ let se = serde_json::to_value(&StreamEvent::ContentBlockStart {
+ index: 1,
+ content_block: ContentDeltaEvent::InputJsonDelta {
+ partial_json: "".into(),
+ },
+ })
+ .expect("se content_block_start_tool_use");
+ assert_eq!(
+ se,
+ content_block_start_tool_use(),
+ "content_block_start_tool_use"
+ );
+ }
+
+ #[test]
+ fn test_de_content_block_start_tool_use() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&content_block_start_tool_use()).expect("str"),
+ )
+ .expect("deserialize_content_block_start_tool_use");
+ assert!(
+ if let StreamEvent::ContentBlockStart { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize content_block_start_tool_use"
+ );
+ }
+
+ #[test]
+ fn test_se_content_block_delta_text() {
+ let se = serde_json::to_value(&StreamEvent::ContentBlockDelta {
+ index: 0,
+ delta: ContentDeltaEvent::TextDelta {
+ text: "Hello".into(),
+ },
+ })
+ .expect("se content_block_delta_text");
+ assert_eq!(se, content_block_delta_text(), "content_block_delta_text");
+ }
+
+ #[test]
+ fn test_de_content_block_delta_text() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&content_block_delta_text()).expect("str"),
+ )
+ .expect("deserialize_content_block_delta_text");
+ assert!(
+ if let StreamEvent::ContentBlockDelta { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize content_block_delta_text"
+ );
+ }
+
+ #[test]
+ fn test_se_content_block_delta_json() {
+ let se = serde_json::to_value(&StreamEvent::ContentBlockDelta {
+ index: 1,
+ delta: ContentDeltaEvent::InputJsonDelta {
+ partial_json: "{\"location\":\"".into(),
+ },
+ })
+ .expect("se content_block_delta_json");
+ assert_eq!(se, content_block_delta_json(), "content_block_delta_json");
+ }
+
+ #[test]
+ fn test_de_content_block_delta_json() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&content_block_delta_json()).expect("str"),
+ )
+ .expect("deserialize_content_block_delta_json");
+ assert!(
+ if let StreamEvent::ContentBlockDelta { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize content_block_delta_json"
+ );
+ }
+
+ #[test]
+ fn test_se_content_block_stop() {
+ let se = serde_json::to_value(&StreamEvent::ContentBlockStop { index: 0 })
+ .expect("se content_block_stop");
+ assert_eq!(se, content_block_stop(), "content_block_stop");
+ }
+
+ #[test]
+ fn test_de_content_block_stop() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&content_block_stop()).expect("str"),
+ )
+ .expect("deserialize_content_block_stop");
+ assert!(
+ if let StreamEvent::ContentBlockStop { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize content_block_stop"
+ );
+ }
+
+ #[test]
+ fn test_se_message_delta() {
+ let se = serde_json::to_value(&StreamEvent::MessageDelta {
+ delta: MessageResponse {
+ id: Some("abc".into()),
+ r#type: Some("message".into()),
+ container: None,
+ content: Some(Content::Array(vec![])),
+ role: Some(Role::Assistant),
+ context_management: None,
+ model: Some("claude-sonnet-4-5-20250929".into()),
+ stop_sequence: None,
+ stop_reason: None,
+ usage: Some(Usage {
+ cache_creation: None,
+ cache_creation_input_tokens: None,
+ cache_read_input_tokens: None,
+ input_tokens: 472,
+ output_tokens: 2,
+ server_tool_use: None,
+ service_tier: None,
+ }),
+ },
+ usage: None,
+ })
+ .expect("se message_delta");
+ assert_eq!(se, message_delta(), "message_delta");
+ }
+
+ #[test]
+ fn test_de_message_delta() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&message_delta()).expect("str"),
+ )
+ .expect("deserialize_message_delta");
+ assert!(
+ if let StreamEvent::MessageDelta { .. } = de {
+ true
+ } else {
+ false
+ },
+ "deserialize message_delta"
+ );
+ }
+
+ #[test]
+ fn test_se_message_stop() {
+ let se = serde_json::to_value(&StreamEvent::MessageStop).expect("se message_stop");
+ assert_eq!(se, message_stop(), "message_stop");
+ }
+
+ #[test]
+ fn test_de_message_stop() {
+ let de = serde_json::from_str::<StreamEvent>(
+ &serde_json::to_string(&message_stop()).expect("str"),
+ )
+ .expect("deserialize_message_stop");
+ assert!(
+ if let StreamEvent::MessageStop = de {
+ true
+ } else {
+ false
+ },
+ "deserialize message_stop"
+ );
+ }
+
+ #[test]
+ fn test_se_ping() {
+ let se = serde_json::to_value(&StreamEvent::Ping).expect("se ping");
+ assert_eq!(se, ping(), "ping");
+ }
+
+ #[test]
+ fn test_de_ping() {
+ let de = serde_json::from_str::<StreamEvent>(&serde_json::to_string(&ping()).expect("str"))
+ .expect("deserialize_ping");
+ assert!(
+ if let StreamEvent::Ping = de {
+ true
+ } else {
+ false
+ },
+ "deserialize ping"
+ );
+ }
+}
diff --git a/rust/cloud-storage/document_cognition_service/justfile b/rust/cloud-storage/document_cognition_service/justfile
index 24f8b4a498..1237dc28ac 100644
--- a/rust/cloud-storage/document_cognition_service/justfile
+++ b/rust/cloud-storage/document_cognition_service/justfile
@@ -22,7 +22,7 @@ debug:
RUST_LOG=document_cognition_service=debug,ai=debug,ai_tools=debug,info cargo run --features macro_middleware/local_auth
trace:
- RUST_LOG=document_cognition_service=trace,ai=trace,ai_tools=debug,info cargo run --features macro_middleware/local_auth
+ RUST_LOG=document_cognition_service=trace,ai=trace,ai_tools=debug,anthropic=debug,info, cargo run --features macro_middleware/local_auth
dev-lq:
cargo run --features macro_middleware/local_auth,local_queue
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 97c9f5891a..21d3e28254 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
@@ -6,6 +6,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::model::chats::ChatResponse;
use crate::model::ws::{StreamError, StreamWebSocketError};
use crate::{
@@ -330,7 +331,7 @@ pub async fn handle_send_chat_message(
}
})?;
let is_first_message = chat.messages.is_empty();
- let model = incoming_message.model;
+ let model = ONE_MODEL;
let user_message_id =
store_incoming_message(ctx.clone(), user_id, &chat, model, &incoming_message)
diff --git a/rust/cloud-storage/document_cognition_service/src/core/model.rs b/rust/cloud-storage/document_cognition_service/src/core/model.rs
index 2225ad51dd..a4ad17ecbd 100644
--- a/rust/cloud-storage/document_cognition_service/src/core/model.rs
+++ b/rust/cloud-storage/document_cognition_service/src/core/model.rs
@@ -1,7 +1,9 @@
use ai::types::Model;
-pub static CHAT_MODELS: &[Model] = &[Model::Claude4Sonnet];
+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::Claude4Sonnet;
+pub static FALLBACK_MODEL: Model = Model::Claude45Haiku;
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip
index e35be9759d..8ea92db63a 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml b/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
index c3bf549068..7f02489f42 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/Cargo.toml
@@ -30,7 +30,7 @@ sha2 = { workspace = true }
sqs_client = { path = "../sqs_client" }
tempfile = "3.19.1"
tokio = { workspace = true }
-tokio-stream = "0.1.17"
+tokio-stream = { workspace = true }
tokio-util = { workspace = true }
walkdir = "2.3.2"
zip = { workspace = true }