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.

[1/3] feat(anthropic): Add support for anthropic server tools (#725)

Eric Hayes3281c4b09989
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index b1dd7f3fb0..66d5601b7c 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -228,12 +228,13 @@ dependencies = [
[[package]]
name = "anthropic"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"async-openai",
"async-stream",
"chrono",
"futures",
+ "lazy_static",
"rand 0.9.0",
"reqwest",
"reqwest-eventsource",
diff --git a/rust/cloud-storage/ai/src/types/client/anthropic.rs b/rust/cloud-storage/ai/src/types/client/anthropic.rs
index f10adab210..3d31da6d51 100644
--- a/rust/cloud-storage/ai/src/types/client/anthropic.rs
+++ b/rust/cloud-storage/ai/src/types/client/anthropic.rs
@@ -28,6 +28,6 @@ impl Client for AnthropicClient {
if extensions.is_some() {
tracing::warn!("extensions are not yet supported");
}
- Ok(self.inner.chat().create_stream_openai(request).await)
+ Ok(self.inner.chat().create_stream_openai_lossy(request).await)
}
}
diff --git a/rust/cloud-storage/anthropic/Cargo.toml b/rust/cloud-storage/anthropic/Cargo.toml
index af2f97c67f..2d0897b4df 100644
--- a/rust/cloud-storage/anthropic/Cargo.toml
+++ b/rust/cloud-storage/anthropic/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2024"
name = "anthropic"
publish = false
-version = "0.1.0"
+version = "0.2.0"
[features]
default = ["openai"]
@@ -26,3 +26,4 @@ tracing = { workspace = true }
tokio-stream = { workspace = true }
async-openai = { workspace = true, optional = true}
chrono.workspace = true
+lazy_static = {workspace = true}
diff --git a/rust/cloud-storage/anthropic/examples/chat.rs b/rust/cloud-storage/anthropic/examples/chat.rs
index 616a1eb3c5..f4c6205b23 100644
--- a/rust/cloud-storage/anthropic/examples/chat.rs
+++ b/rust/cloud-storage/anthropic/examples/chat.rs
@@ -5,7 +5,7 @@ use anthropic::client::Client;
use anthropic::types::request::{
CreateMessageRequestBody, RequestContent, RequestMessage, Role, SystemPrompt,
};
-use anthropic::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use anthropic::types::response::{ContentDeltaEvent, StreamEvent};
use futures::StreamExt;
#[tokio::main]
diff --git a/rust/cloud-storage/anthropic/examples/chat_openai.rs b/rust/cloud-storage/anthropic/examples/chat_openai.rs
index d74218aa0a..1ac5ff304f 100644
--- a/rust/cloud-storage/anthropic/examples/chat_openai.rs
+++ b/rust/cloud-storage/anthropic/examples/chat_openai.rs
@@ -2,7 +2,7 @@ use std::io::Write;
use std::process::exit;
use anthropic::client::Client;
-use anthropic::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use anthropic::types::response::{ContentDeltaEvent, StreamEvent};
use async_openai::types::{
ChatCompletionRequestAssistantMessage, ChatCompletionRequestAssistantMessageContent,
ChatCompletionRequestMessage, ChatCompletionRequestSystemMessageArgs,
diff --git a/rust/cloud-storage/anthropic/examples/only_openai_chat.rs b/rust/cloud-storage/anthropic/examples/only_openai_chat.rs
index 09976ecd97..54916109e2 100644
--- a/rust/cloud-storage/anthropic/examples/only_openai_chat.rs
+++ b/rust/cloud-storage/anthropic/examples/only_openai_chat.rs
@@ -19,7 +19,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
println!("{:#?}", request);
let client = anthropic::client::Client::dangerously_try_from_env();
- let mut stream = client.chat().create_stream_openai(request).await;
+ let mut stream = client.chat().create_stream_openai_lossy(request).await;
let mut lock = stdout().lock();
while let Some(result) = stream.next().await {
diff --git a/rust/cloud-storage/anthropic/examples/only_openai_tools.rs b/rust/cloud-storage/anthropic/examples/only_openai_tools.rs
index 9085da3cfa..882cf6a6e3 100644
--- a/rust/cloud-storage/anthropic/examples/only_openai_tools.rs
+++ b/rust/cloud-storage/anthropic/examples/only_openai_tools.rs
@@ -52,7 +52,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.build()?;
let client = anthropic::client::Client::dangerously_try_from_env();
- let mut stream = client.chat().create_stream_openai(request).await;
+ let mut stream = client.chat().create_stream_openai_lossy(request).await;
let tool_call_states: Arc<Mutex<HashMap<(u32, u32), ChatCompletionMessageToolCall>>> =
Arc::new(Mutex::new(HashMap::new()));
@@ -181,7 +181,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.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 stream =
+ client.chat().create_stream_openai_lossy(request).await;
let mut response_content = String::new();
let mut lock = stdout().lock();
diff --git a/rust/cloud-storage/anthropic/examples/server_tool.rs b/rust/cloud-storage/anthropic/examples/server_tool.rs
new file mode 100644
index 0000000000..f272227a0d
--- /dev/null
+++ b/rust/cloud-storage/anthropic/examples/server_tool.rs
@@ -0,0 +1,106 @@
+use anthropic::prelude::WEB_SEARCH_TOOL;
+use std::io::Write;
+use std::process::exit;
+
+use anthropic::client::Client;
+use anthropic::types::request::{
+ CreateMessageRequestBody, RequestContent, RequestMessage, Role, SystemPrompt,
+};
+use anthropic::types::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 a helpful AI assistant in a CLI based demo. Use web search tool eagerly".into(),
+ ));
+ request.model = "claude-haiku-4-5".into();
+ request.tools = Some(vec![WEB_SEARCH_TOOL.clone().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();
+
+ // let mut out = OpenOptions::new()
+ // .write(true)
+ // .create(true)
+ // .open("stream.json")
+ // .unwrap();
+
+ while let Some(event) = stream.next().await {
+ // if let Ok(e) = event {
+ // write!(out, "\n{}\n", serde_json::to_string_pretty(&e).unwrap());
+ // } else {
+ // write!(out, "{:#?}", event.unwrap_err());
+ // }
+ 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,
+ ContentDeltaEvent::CitationsDelta { .. } => "[Citation]".into(),
+ ContentDeltaEvent::WebSearchToolResult(web_search_result) => {
+ format!("{:#?}", web_search_result)
+ }
+
+ ContentDeltaEvent::ServerToolUse(tool) => {
+ format!("{:#?}", tool)
+ }
+ _ => "".into(),
+ },
+ StreamEvent::Error { error } => format!("error: {:?}", error),
+ StreamEvent::ContentBlockStart { content_block, .. } => match content_block {
+ ContentDeltaEvent::ServerToolUse(tool) => {
+ format!("{:#?}", tool)
+ }
+ ContentDeltaEvent::WebSearchToolResult(web_search_result) => {
+ format!("{:#?}", web_search_result)
+ }
+ _ => "".into(),
+ },
+ _ => "".into(),
+ };
+ 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/tools.rs b/rust/cloud-storage/anthropic/examples/tools.rs
index 82dfa8af0d..962f8f4616 100644
--- a/rust/cloud-storage/anthropic/examples/tools.rs
+++ b/rust/cloud-storage/anthropic/examples/tools.rs
@@ -39,11 +39,14 @@ async fn main() {
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,
- }]);
+ request.tools = Some(vec![
+ ClientTool {
+ description: Some("get the weather".into()),
+ name: "check_weather".into(),
+ input_schema: weather_tool,
+ }
+ .into(),
+ ]);
let mut out = std::io::stdout();
let mut stream = client.chat().create_stream(request).await;
let mut tool_json = String::new();
diff --git a/rust/cloud-storage/anthropic/examples/tools_openai.rs b/rust/cloud-storage/anthropic/examples/tools_openai.rs
index 48cc7fedff..43d3c844f4 100644
--- a/rust/cloud-storage/anthropic/examples/tools_openai.rs
+++ b/rust/cloud-storage/anthropic/examples/tools_openai.rs
@@ -1,5 +1,5 @@
use anthropic::client::Client;
-use anthropic::types::stream_response::{ContentDeltaEvent, StreamEvent};
+use anthropic::types::response::{ContentDeltaEvent, StreamEvent};
use async_openai::types::{
ChatCompletionRequestUserMessage, ChatCompletionRequestUserMessageContent,
ChatCompletionToolArgs, ChatCompletionToolType, CreateChatCompletionRequestArgs,
diff --git a/rust/cloud-storage/anthropic/src/client/chat.rs b/rust/cloud-storage/anthropic/src/client/chat.rs
index caa6a72e4f..3db3dcd7a0 100644
--- a/rust/cloud-storage/anthropic/src/client/chat.rs
+++ b/rust/cloud-storage/anthropic/src/client/chat.rs
@@ -6,7 +6,7 @@ use std::pin::Pin;
use super::Client;
use crate::error::AnthropicError;
use crate::types::request::CreateMessageRequestBody;
-use crate::types::stream_response::StreamEvent;
+use crate::types::response::StreamEvent;
pub type MessageCompletionResponseStream =
Pin<Box<dyn Stream<Item = Result<StreamEvent, AnthropicError>> + Send>>;
diff --git a/rust/cloud-storage/anthropic/src/openai/mod.rs b/rust/cloud-storage/anthropic/src/openai/mod.rs
index 2ac38833e6..b0733369d6 100644
--- a/rust/cloud-storage/anthropic/src/openai/mod.rs
+++ b/rust/cloud-storage/anthropic/src/openai/mod.rs
@@ -1,2 +1,3 @@
pub mod request;
+pub mod stream_extension;
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
index c4039b8836..bbfa7c9dda 100644
--- a/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
+++ b/rust/cloud-storage/anthropic/src/openai/request/conversions.rs
@@ -1,5 +1,5 @@
use crate::{
- prelude::ImageSource,
+ prelude::{ClientTool, ImageSource},
types::request::{self, SystemPrompt},
};
use async_openai::types::{
@@ -328,11 +328,11 @@ impl From<ChatCompletionToolChoiceOption> for request::ToolChoice {
impl From<ChatCompletionTool> for request::Tool {
fn from(value: ChatCompletionTool) -> Self {
- Self {
+ Self::Client(ClientTool {
description: value.function.description,
input_schema: value.function.parameters.unwrap_or_default(),
name: value.function.name,
- }
+ })
}
}
diff --git a/rust/cloud-storage/anthropic/src/openai/request/mod.rs b/rust/cloud-storage/anthropic/src/openai/request/mod.rs
index a29ed27628..3040c2607c 100644
--- a/rust/cloud-storage/anthropic/src/openai/request/mod.rs
+++ b/rust/cloud-storage/anthropic/src/openai/request/mod.rs
@@ -1,5 +1,8 @@
mod conversions;
+mod request_extension;
+
pub use conversions::*;
+pub use request_extension::*;
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/anthropic/src/openai/request/request_extension.rs b/rust/cloud-storage/anthropic/src/openai/request/request_extension.rs
new file mode 100644
index 0000000000..9d54d16c52
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/request/request_extension.rs
@@ -0,0 +1,49 @@
+use crate::types::request::WEB_SEARCH_TOOL;
+
+/// Request extensions are functionality that is supported by the anthropic API but not supported by OpenAI/completions/v1
+/// These will affect the request sent to anthropic
+///
+/// Server tools are the main features we need to support that are only supported by anthropic but not OpenAI
+
+#[derive(Clone, Debug, Copy)]
+pub enum AnthropicRequestExtension {
+ /// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>
+ WebSearchTool,
+ // https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool
+ // FetchTool,
+}
+
+#[derive(Clone, Debug)]
+pub struct AnthropicRequestExtensions(pub Vec<AnthropicRequestExtension>);
+
+impl AnthropicRequestExtensions {
+ pub fn extend_request(
+ &self,
+ mut request: crate::types::request::CreateMessageRequestBody,
+ ) -> crate::types::request::CreateMessageRequestBody {
+ self.0
+ .iter()
+ .for_each(|extension| extension.extend_request(&mut request));
+ request
+ }
+}
+
+impl AnthropicRequestExtension {
+ pub(crate) fn extend_request(
+ &self,
+ request: &mut crate::types::request::CreateMessageRequestBody,
+ ) {
+ match self {
+ Self::WebSearchTool => {
+ if let Some(ref mut tools) = request.tools {
+ let search = WEB_SEARCH_TOOL.clone().into();
+ if !tools.iter().any(|t| t == &search) {
+ tools.push(search);
+ }
+ } else {
+ request.tools = Some(vec![WEB_SEARCH_TOOL.clone().into()])
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/anthropic/src/openai/request/test.rs b/rust/cloud-storage/anthropic/src/openai/request/test.rs
index 0f8ee65d06..5baf141229 100644
--- a/rust/cloud-storage/anthropic/src/openai/request/test.rs
+++ b/rust/cloud-storage/anthropic/src/openai/request/test.rs
@@ -215,7 +215,7 @@ fn expected_failed_tool_calls() -> CreateMessageRequestBody {
temperature: None,
thinking: None,
tool_choice: None,
- tools: Some(vec![Tool {
+ tools: Some(vec![ClientTool {
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!({
@@ -262,7 +262,7 @@ fn expected_failed_tool_calls() -> CreateMessageRequestBody {
"title": "ListDocuments",
"type": "object"
})
- }]),
+ }.into()]),
top_k: None,
top_p: None,
}
diff --git a/rust/cloud-storage/anthropic/src/openai/stream_extension.rs b/rust/cloud-storage/anthropic/src/openai/stream_extension.rs
new file mode 100644
index 0000000000..c4cf7b1d10
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/openai/stream_extension.rs
@@ -0,0 +1,36 @@
+use crate::types::response::{Citation, ServerToolUse, WebSearchResponse};
+use async_openai::error::OpenAIError;
+use async_openai::types::CreateChatCompletionStreamResponse;
+use futures::Stream;
+use std::pin::Pin;
+
+/// Items that are returned in an Anthropic stream but not supported by OpenAI
+#[derive(Clone, Debug, PartialEq)]
+pub enum AnthropicResponseExtension {
+ ServerToolUse(ServerToolUse),
+ Citation(Citation),
+ WebSearchToolResponse(WebSearchResponse),
+}
+
+/// A standard OpenAI response item or an item only sent by Anthropic
+#[derive(Clone, Debug, PartialEq)]
+pub enum ExtendedAnthropicStreamItem {
+ OpenAI(CreateChatCompletionStreamResponse),
+ Extension(AnthropicResponseExtension),
+}
+
+impl From<CreateChatCompletionStreamResponse> for ExtendedAnthropicStreamItem {
+ fn from(value: CreateChatCompletionStreamResponse) -> Self {
+ Self::OpenAI(value)
+ }
+}
+
+impl From<AnthropicResponseExtension> for ExtendedAnthropicStreamItem {
+ fn from(value: AnthropicResponseExtension) -> Self {
+ Self::Extension(value)
+ }
+}
+
+/// Full stream type of mixed openai items and anthropic items
+pub type ExtendedStream =
+ Pin<Box<dyn Stream<Item = Result<ExtendedAnthropicStreamItem, OpenAIError>> + Send>>;
diff --git a/rust/cloud-storage/anthropic/src/openai/stream_response.rs b/rust/cloud-storage/anthropic/src/openai/stream_response.rs
index d86aa80c64..283bc4c798 100644
--- a/rust/cloud-storage/anthropic/src/openai/stream_response.rs
+++ b/rust/cloud-storage/anthropic/src/openai/stream_response.rs
@@ -1,8 +1,9 @@
+use super::request::AnthropicRequestExtensions;
+use super::stream_extension::{ExtendedAnthropicStreamItem, ExtendedStream};
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::openai::stream_extension::AnthropicResponseExtension;
+use crate::types::response::{ContentDeltaEvent, StopReason, StreamEvent, Usage};
use crate::{client::chat::Chat, prelude::CreateMessageRequestBody};
use async_openai::error::{ApiError, OpenAIError};
use async_openai::types::{
@@ -107,7 +108,7 @@ fn map_stop_reason(stop_reason: StopReason) -> FinishReason {
}
}
-pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletionResponseStream {
+fn map_stream_extended(mut stream: MessageCompletionResponseStream) -> ExtendedStream {
Box::pin(stream! {
let mut message_id: Option<String> = None;
let mut model: Option<String> = None;
@@ -145,7 +146,7 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
create_role_delta(Role::Assistant),
None,
None,
- ))
+ ).into())
}
StreamEvent::ContentBlockStart { content_block, ..} => {
if let ContentDeltaEvent::ToolUse { name, id, .. } = content_block {
@@ -157,6 +158,14 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
}
StreamEvent::ContentBlockDelta { index, delta } => {
match delta {
+ ContentDeltaEvent::CitationsDelta { citation } => {
+ Ok(
+ AnthropicResponseExtension::Citation(citation).into()
+ )
+ }
+ ContentDeltaEvent::WebSearchToolResult(web_search_response) => {
+ Ok(AnthropicResponseExtension::WebSearchToolResponse(web_search_response).into())
+ }
ContentDeltaEvent::TextDelta { text } | ContentDeltaEvent::StartTextDelta { text } => {
Ok(create_response(
&message_id.clone().unwrap_or_default(),
@@ -166,7 +175,7 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
create_content_delta(text),
None,
None,
- ))
+ ).into())
}
ContentDeltaEvent::ThinkingDelta { thinking } => {
// OpenAI doesn't have thinking blocks, skip or include as content
@@ -178,7 +187,7 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
create_content_delta(format!("[Thinking] {}", thinking)),
None,
None,
- ))
+ ).into())
}
ContentDeltaEvent::ToolUse { id, name, input } => {
// Map to OpenAI tool call
@@ -196,7 +205,10 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
),
None,
None,
- ))
+ ).into())
+ }
+ ContentDeltaEvent::ServerToolUse(server_tool_use) => {
+ Ok(AnthropicResponseExtension::ServerToolUse(server_tool_use).into())
}
ContentDeltaEvent::InputJsonDelta { partial_json } => {
// Stream partial JSON for tool call arguments
@@ -214,8 +226,9 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
),
None,
None,
- ))
+ ).into())
}
+
ContentDeltaEvent::SignatureDelta { .. } => {
// Skip signature deltas as OpenAI doesn't have an equivalent
continue;
@@ -237,7 +250,7 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
create_empty_delta(),
finish_reason,
usage.map(Into::into),
- ))
+ ).into())
}
StreamEvent::MessageStop => {
Ok(create_response(
@@ -248,7 +261,7 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
create_empty_delta(),
Some(FinishReason::Stop),
None,
- ))
+ ).into())
}
StreamEvent::Ping => {
// Skip ping events
@@ -269,6 +282,17 @@ pub fn map_stream(mut stream: MessageCompletionResponseStream) -> ChatCompletion
})
}
+/// Discard items that are unsupported by openai
+fn map_stream_lossy(stream: MessageCompletionResponseStream) -> ChatCompletionResponseStream {
+ Box::pin(map_stream_extended(stream).filter_map(|item| async move {
+ match item {
+ Err(e) => Some(Err(e)),
+ Ok(ExtendedAnthropicStreamItem::OpenAI(item)) => Some(Ok(item)),
+ Ok(_) => None,
+ }
+ }))
+}
+
impl From<Usage> for async_openai::types::CompletionUsage {
fn from(value: Usage) -> async_openai::types::CompletionUsage {
Self {
@@ -282,7 +306,8 @@ impl From<Usage> for async_openai::types::CompletionUsage {
}
impl<'c> Chat<'c> {
- pub async fn create_stream_openai<I>(&self, request: I) -> ChatCompletionResponseStream
+ /// create an openai/completions/v1 compatible stream discarding events that are unsupported
+ pub async fn create_stream_openai_lossy<I>(&self, request: I) -> ChatCompletionResponseStream
where
I: Into<CreateMessageRequestBody>,
{
@@ -291,13 +316,35 @@ impl<'c> Chat<'c> {
self.create_stream_openai_unchecked(request).await
}
- pub async fn create_stream_openai_unchecked<I>(
+ /// create an openai/completion/v1 compatible stream wrapping items in [`ExtendedAnthropicStreamItem`]
+ pub async fn create_stream_openai_extended<I>(
+ &self,
+ request: I,
+ extensions: &AnthropicRequestExtensions,
+ ) -> ExtendedStream
+ where
+ I: Into<CreateMessageRequestBody>,
+ {
+ let mut request = request.into();
+ request.stream = Some(true);
+ let request = extensions.extend_request(request);
+ self.create_stream_extended_unchecked(request).await
+ }
+
+ pub(crate) async fn create_stream_extended_unchecked<I>(&self, request: I) -> ExtendedStream
+ where
+ I: Serialize + std::fmt::Debug,
+ {
+ map_stream_extended(self.inner.post_stream("/v1/messages", request).await)
+ }
+
+ pub(crate) async fn create_stream_openai_unchecked<I>(
&self,
request: I,
) -> ChatCompletionResponseStream
where
I: Serialize + std::fmt::Debug,
{
- map_stream(self.inner.post_stream("/v1/messages", request).await)
+ map_stream_lossy(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
index fa22d0d1fd..accee359b7 100644
--- a/rust/cloud-storage/anthropic/src/prelude.rs
+++ b/rust/cloud-storage/anthropic/src/prelude.rs
@@ -2,7 +2,6 @@ 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
index fcb205c8f5..e0062185c4 100644
--- a/rust/cloud-storage/anthropic/src/types/mod.rs
+++ b/rust/cloud-storage/anthropic/src/types/mod.rs
@@ -1,4 +1,2 @@
pub mod request;
-pub mod request_util;
pub mod response;
-pub mod stream_response;
diff --git a/rust/cloud-storage/anthropic/src/types/request/mod.rs b/rust/cloud-storage/anthropic/src/types/request/mod.rs
new file mode 100644
index 0000000000..f421652bc7
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/request/mod.rs
@@ -0,0 +1,6 @@
+mod server_tools;
+mod types;
+mod util;
+
+pub use server_tools::*;
+pub use types::*;
diff --git a/rust/cloud-storage/anthropic/src/types/request/server_tools.rs b/rust/cloud-storage/anthropic/src/types/request/server_tools.rs
new file mode 100644
index 0000000000..dcaa1d22a5
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/request/server_tools.rs
@@ -0,0 +1,11 @@
+use super::types::ServerTool;
+use lazy_static::lazy_static;
+use serde_json::Value;
+
+lazy_static! {
+ pub static ref WEB_SEARCH_TOOL: ServerTool = ServerTool {
+ name: "web_search".into(),
+ r#type: "web_search_20250305".into(),
+ args: Value::Null,
+ };
+}
diff --git a/rust/cloud-storage/anthropic/src/types/request.rs b/rust/cloud-storage/anthropic/src/types/request/types.rs
similarity index 90%
rename from rust/cloud-storage/anthropic/src/types/request.rs
rename to rust/cloud-storage/anthropic/src/types/request/types.rs
index 6dbcc179bb..0c275463f3 100644
--- a/rust/cloud-storage/anthropic/src/types/request.rs
+++ b/rust/cloud-storage/anthropic/src/types/request/types.rs
@@ -140,17 +140,35 @@ pub enum ToolChoice {
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
-pub struct Tool {
+#[serde(untagged)]
+pub enum Tool {
+ /// A tool that is round-tripped (sent to anthropic, "called" by anthropic,
+ /// code executed by us, result sent back to anthropic in a 2nd request)
+ Client(ClientTool),
+ /// A tool that's called, and executed in a single request to anthropic
+ Server(ServerTool),
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
+pub struct ClientTool {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub input_schema: serde_json::Value,
}
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
+pub struct ServerTool {
+ pub r#type: String,
+ pub name: String,
+ #[serde(flatten)]
+ pub args: 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
+ /// <https://docs.claude.com/en/docs/about-claude/models/overview>
pub model: String,
/// Input messages.
pub messages: Vec<RequestMessage>,
diff --git a/rust/cloud-storage/anthropic/src/types/request_util.rs b/rust/cloud-storage/anthropic/src/types/request/util.rs
similarity index 52%
rename from rust/cloud-storage/anthropic/src/types/request_util.rs
rename to rust/cloud-storage/anthropic/src/types/request/util.rs
index d3d9ae14ce..bcce76574d 100644
--- a/rust/cloud-storage/anthropic/src/types/request_util.rs
+++ b/rust/cloud-storage/anthropic/src/types/request/util.rs
@@ -1,4 +1,6 @@
-use super::request::*;
+use std::collections::BTreeMap;
+
+use super::types::*;
impl RequestContentKind {
pub fn text(text: String) -> Self {
@@ -56,3 +58,51 @@ impl RequestMessage {
}
}
}
+
+impl From<ServerTool> for Tool {
+ fn from(value: ServerTool) -> Self {
+ Self::Server(value)
+ }
+}
+
+impl From<ClientTool> for Tool {
+ fn from(value: ClientTool) -> Self {
+ Self::Client(value)
+ }
+}
+
+impl Tool {
+ pub fn name(&self) -> &str {
+ match self {
+ Self::Client(ClientTool { name, .. }) => name.as_str(),
+ Self::Server(ServerTool { name, .. }) => name.as_str(),
+ }
+ }
+}
+
+impl CreateMessageRequestBody {
+ // openapi completions/v1 does not support ServerTools
+ // this helper lets tools be directly added to the anthropic request
+ // additional tools are deduplicated
+ pub fn with_additional_tools<I, T>(mut self, tools: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<Tool>,
+ {
+ match self.tools {
+ Some(ref mut existing) => {
+ existing.append(&mut tools.into_iter().map(Into::into).collect());
+ let deduped = existing
+ .clone()
+ .into_iter()
+ .map(|t| (t.name().to_owned(), t))
+ .collect::<BTreeMap<_, _>>()
+ .into_values()
+ .collect::<Vec<_>>();
+ self.tools = Some(deduped);
+ }
+ None => self.tools = Some(tools.into_iter().map(Into::into).collect()),
+ }
+ self
+ }
+}
diff --git a/rust/cloud-storage/anthropic/src/types/response/citation.rs b/rust/cloud-storage/anthropic/src/types/response/citation.rs
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/rust/cloud-storage/anthropic/src/types/response/mod.rs b/rust/cloud-storage/anthropic/src/types/response/mod.rs
new file mode 100644
index 0000000000..5d99968f60
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/response/mod.rs
@@ -0,0 +1,7 @@
+mod stream_types;
+mod types;
+mod web_search;
+
+pub use stream_types::*;
+pub use types::*;
+pub use web_search::*;
diff --git a/rust/cloud-storage/anthropic/src/types/stream_response.rs b/rust/cloud-storage/anthropic/src/types/response/stream_types.rs
similarity index 95%
rename from rust/cloud-storage/anthropic/src/types/stream_response.rs
rename to rust/cloud-storage/anthropic/src/types/response/stream_types.rs
index d015ad4d2f..a92d91593d 100644
--- a/rust/cloud-storage/anthropic/src/types/stream_response.rs
+++ b/rust/cloud-storage/anthropic/src/types/response/stream_types.rs
@@ -1,5 +1,8 @@
-use super::response::MessageResponse;
-use super::response::Usage;
+use crate::prelude::ServerToolUse;
+
+use super::web_search::WebSearchResponse;
+
+use super::{MessageResponse, Usage};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -51,6 +54,7 @@ pub enum ContentDeltaEvent {
name: String,
input: serde_json::Value,
},
+ ServerToolUse(ServerToolUse),
/// partial json for a tool call
InputJsonDelta {
partial_json: String,
@@ -61,6 +65,20 @@ pub enum ContentDeltaEvent {
SignatureDelta {
signature: String,
},
+ CitationsDelta {
+ citation: Citation,
+ },
+ WebSearchToolResult(WebSearchResponse),
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
+pub struct Citation {
+ pub r#type: String,
+ pub cited_text: Option<String>,
+ pub document_title: Option<String>,
+ pub document_index: Option<u32>,
+ pub start_char_index: Option<u32>,
+ pub end_char_index: Option<u32>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
diff --git a/rust/cloud-storage/anthropic/src/types/response.rs b/rust/cloud-storage/anthropic/src/types/response/types.rs
similarity index 94%
rename from rust/cloud-storage/anthropic/src/types/response.rs
rename to rust/cloud-storage/anthropic/src/types/response/types.rs
index a9b1ca6fb1..e1583b9ccd 100644
--- a/rust/cloud-storage/anthropic/src/types/response.rs
+++ b/rust/cloud-storage/anthropic/src/types/response/types.rs
@@ -1,4 +1,4 @@
-use super::request::Role;
+use crate::types::request::Role;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
@@ -7,6 +7,7 @@ pub enum ResponseContentKind {
Text(TextResponse),
Thinking(ThinkingResponse),
ToolUse(ToolUse),
+ ServerToolUse(ServerToolUse),
// there are many more options that could be implemented here
// https://docs.claude.com/en/api/messages#responsewebfetchtoolresultblock
}
@@ -18,12 +19,6 @@ pub enum Content {
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,
diff --git a/rust/cloud-storage/anthropic/src/types/response/web_search.rs b/rust/cloud-storage/anthropic/src/types/response/web_search.rs
new file mode 100644
index 0000000000..d61029c505
--- /dev/null
+++ b/rust/cloud-storage/anthropic/src/types/response/web_search.rs
@@ -0,0 +1,17 @@
+use serde::{Deserialize, Serialize};
+
+/// Web search response content returned by Claude when using the web_search tool
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct WebSearchResponse {
+ /// The search query that was executed
+ /// Array of search results
+ pub content: Vec<SearchResult>,
+}
+
+/// A single search result from web search
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum SearchResult {
+ WebSearchResult { title: String, url: String },
+}